// Arup Guha
// 2/22/2024
// Solution to Kattis Problem: Grid (sorry I called this maze =))

import java.util.*;

public class maze {

	// Directions I can jump.
	final public static int[] DX = {-1,0,0,1};
	final public static int[] DY = {0,-1,1,0};

	// Stores grid.
	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 grid.
		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';
		}
		
		// Run it!
		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) {
		
			// Extra current location.
			int cur = q.poll();
			int cX = cur/c;
			int cY = cur%c;
			
			// Try jumping in all four directions.
			for (int i=0; i<DX.length; i++) {
				
				// The grid number is how far we jump so we can just multiply by 
				// the direction.
				int nX = cX + DX[i]*g[cX][cY];
				int nY = cY + DY[i]*g[cX][cY];
				
				// Reasons not to explore from a location.
				if (!inbounds(nX, nY)) continue;
				if (dist[nX*c+nY] != -1) continue;
				
				// It's new, so add to the queue and store the distance.
				dist[nX*c+nY] = dist[cur] + 1;
				q.offer(nX*c+nY);
			}
		}
		
		// This is what we want.
		return dist[e];
	}
	
	public static boolean inbounds(int x, int y) {
		return x>=0 && x<r && y>=0 && y <c;
	}
}