#include <stdio.h>
#include <utility>
#include <queue>
int result = -1; // 결과값을 저장할 변수입니다.
int row, col; // 미로의 크기를 저장할 변수입니다.
char map[101][101] = {0,}; // 미로의 형태를 저장할 배열입니다.
int visit[101][101] = {0,}; // 각 칸을 방문했는지 여부를 저장할 배열입니다.
std::queue<std::pair<int, int>> q; // BFS 알고리즘에 사용할 큐입니다.
void BFS()
{
q.push(std::make_pair(0, 0)); // 시작점을 큐에 추가합니다.
visit[0][0] = 1; // 시작점을 방문했음을 표시합니다.
while (!q.empty())
{
int cur_row = q.front().first; // 큐에서 현재 위치의 행을 가져옵니다.
int cur_col = q.front().second; // 큐에서 현재 위치의 열을 가져옵니다.
int cur_score = visit[cur_row][cur_col]; // 현재 위치까지의 이동 횟수를 가져옵니다.
// 상 방향으로 이동 가능한 경우를 처리합니다.
if (cur_row > 0 &&
map[cur_row-1][cur_col] == '1' &&
(visit[cur_row-1][cur_col] == 0 || visit[cur_row-1][cur_col] > cur_score + 1))
{
q.push(std::make_pair(cur_row-1, cur_col));
visit[cur_row-1][cur_col] = visit[cur_row][cur_col] + 1;
}
// 하 방향으로 이동 가능한 경우를 처리합니다.
if (cur_row < row - 1 &&
map[cur_row+1][cur_col] == '1' &&
(visit[cur_row+1][cur_col] == 0 || visit[cur_row+1][cur_col] > cur_score + 1))
{
q.push(std::make_pair(cur_row+1, cur_col));
visit[cur_row+1][cur_col] = visit[cur_row][cur_col] + 1;
}
// 좌 방향으로 이동 가능한 경우를 처리합니다.
if (cur_col > 0 &&
map[cur_row][cur_col-1] == '1' &&
(visit[cur_row][cur_col-1] == 0 || visit[cur_row][cur_col-1] > cur_score + 1))
{
q.push(std::make_pair(cur_row, cur_col-1));
visit[cur_row][cur_col-1] = visit[cur_row][cur_col] + 1;
}
// 우 방향으로 이동 가능한 경우를 처리합니다.
if (cur_col < col - 1 &&
map[cur_row][cur_col+1] == '1' &&
(visit[cur_row][cur_col+1] == 0 || visit[cur_row][cur_col+1] > cur_score + 1))
{
q.push(std::make_pair(cur_row, cur_col+1));
visit[cur_row][cur_col+1] = visit[cur_row][cur_col] + 1;
}
q.pop(); // 현재 위치를 큐에서 제거합니다.
}
}
int main()
{
scanf("%d %d", &row, &col); // 미로의 크기를 입력받습니다.
for (int rowIdx = 0; rowIdx < row; rowIdx++)
{
scanf("%s", &map[rowIdx]); // 미로의 형태를 입력받습니다.
}
BFS(); // BFS 알고리즘을 실행합니다.
printf("%d\n", visit[row-1][col-1]); // 결과값(최소의 칸 수)을 출력합니다.
return 0;
}