// Arup Guha
// 2/22/2024
// Solution to Kattis Problem: Grid
// https://open.kattis.com/problems/grid

import java.util.*;

public class grid {

	final public static int[] DX = {-1,0,0,1};
	final public static int[] DY = {0,-1,1,0};
	
	public static int r;
	public static int c;
	public static int[][] g;
	
	public static void main(String[] args) {
	
		Scanner stdin = new Scanner(System.in);
		r = stdin.nextInt();
		c = stdin.nextInt();
		g = new int[r][c];
		
		// Read in graph.
		for (int i=0; i<r; i++) {
			char[] tmp = stdin.next().toCharArray();
			for (int j=0; j<c; j++)
				g[i][j] = tmp[j] - '0';
		}
		
		// Solve via BFS.
		System.out.println(bfs(0, r*c-1));
	}
	
	public static int bfs(int s, int e) {
	
		// Set up.
		ArrayDeque<Integer> q = new ArrayDeque();
		q.offer(s);
		int[] dist = new int[r*c];
		Arrays.fill(dist, -1);
		dist[s] = 0;
		
		// Run BFS.
		while (q.size() > 0) {
		
			// Get next item.
			int cur = q.poll();
			int cX = cur/c;
			int cY = cur%c;
			
			// Try moving in all 4 directions.
			for (int i=0; i<DX.length; i++) {
				
				// Here is were we'd jump to.
				int nX = cX + DX[i]*g[cX][cY];
				int nY = cY + DY[i]*g[cX][cY];
				
				// Reasons not to travel here.
				if (!inbounds(nX, nY)) continue;
				if (dist[nX*c+nY] != -1) continue;
				
				// Update distance, add to queue.
				dist[nX*c+nY] = dist[cur] + 1;
				q.offer(nX*c+nY);
			}
		}
		
		// Ta da!
		return dist[e];
	}
	
	public static boolean inbounds(int x, int y) {
		return x>=0 && x<r && y>=0 && y <c;
	}
}