import java.awt.Point;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Exam2178 {
static int N, M;
static char map[][];
static boolean visit[][];
static Queue<Add> queue = new LinkedList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
map = new char[N][M];
visit = new boolean[N][M];
sc.nextLine();
for (int i = 0; i < N; i++) {
map[i] = sc.nextLine().toCharArray();
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
visit[i][j] = false;
}
}
System.out.println(travling(0, 0, 1));
sc.close();
}
static int travling(int x, int y, int cnt) {
int ret = 100000;
visit[x][y] = true;
if (x == N - 1 && y == M - 1) {
return cnt;
}
// 오
if ((y + 1 < M && map[x][y + 1] == '1' && !visit[x][y + 1])) {
queue.add(new Add(new Point(x, y + 1), cnt + 1));
}
// 아래
if ((x + 1 < N && map[x + 1][y] == '1' && !visit[x + 1][y])) {
queue.add(new Add(new Point(x + 1, y), cnt + 1));
}
// 위
if ((x - 1 >= 0 && map[x - 1][y] == '1' && !visit[x - 1][y])) {
queue.add(new Add(new Point(x - 1, y), cnt + 1));
}
// 왼
if ((y - 1 >= 0 && map[x][y - 1] == '1' && !visit[x][y - 1])) {
queue.add(new Add(new Point(x, y - 1), cnt + 1));
}
while (!queue.isEmpty()) {
Add p = queue.poll();
if (!visit[p.point.x][p.point.y]) {
int result = travling(p.point.x, p.point.y, p.cnt);
if (result != 100000) {
return result;
}
}
}
return ret;
}
}
class Add {
Point point;
int cnt;
public Add(Point point, int cnt) {
super();
this.point = point;
this.cnt = cnt;
}
}