# 본인 풀이
BFS로 풀었고 거의 모범답안에 유사하여 굳이 답안은 추가하지 않았음.
#include<bits/stdc++.h>
using namespace std;
string a[100];
int b[100][100];
int visited[100][100];
int n, m, y, x;
int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
for (int i = 0; i < n; i++){
cin >> a[i];
for (int j = 0; j < a[i].size(); j++){
b[i][j] = a[i][j] - '0';
}
}
queue<pair<int, int>> q;
q.push({0, 0});
visited[0][0] = 1;
while (q.size()){
tie(y, x) = q.front();
q.pop();
for (int i = 0; i < 4; i++){
int ny = y + dy[i];
int nx = x + dx[i];
if(ny < 0 || nx < 0 || ny >= n || nx >= m){
continue;
}
if(b[ny][nx] && visited[ny][nx] == 0){
visited[ny][nx] = visited[y][x] + 1;
q.push({ny, nx});
}
}
}
cout << visited[n - 1][m - 1] << "\n";
return 0;
}