// Arup Guha
// 11/14/2015
// Solution to 2015 SER D1/D2 Problem: Grid

import java.util.*;

public class grid {

	// Directions we can move.
	final public static int[] DX = {-1,0,0,1};
	final public static int[] DY = {0,-1,1,0};
	final public static int NOT_FOUND = -1;

	public static int r;
	public static int c;
	public static int[][] grid;
	public static int[][] dist;

	public static void main(String[] args) {

		Scanner stdin = new Scanner(System.in);
		r = stdin.nextInt();
		c = stdin.nextInt();
		grid = new int[r][c];
		dist = new int[r][c];

		// Read in the grid.
		for (int i=0; i<r; i++) {
			Arrays.fill(dist[i], NOT_FOUND);
			String line = stdin.next();
			for (int j=0; j<c; j++)
				grid[i][j] = line.charAt(j) - '0';
		}

		// Set up BFS.
		LinkedList<Integer> q = new LinkedList<Integer>();
		q.offer(0);
		dist[0][0] = 0;

		// Run BFS.
		while (q.size() > 0) {

			// Get next square.
			int next = q.poll();
			int nX = next/c;
			int nY = next%c;

			// Got it!!!
			if (nX == r-1 && nY == c-1) break;

			// Try going in all four directions.
			for (int i=0; i<DX.length; i++) {

				int x = nX + DX[i]*grid[nX][nY];
				int y = nY + DY[i]*grid[nX][nY];

				// We got to a new place!
				if (inbounds(x,y) && dist[x][y] == -1) {
					dist[x][y] = dist[nX][nY] + 1;
					q.offer(x*c + y);
				}
			}
		}

		// Output result.
		System.out.println(dist[r-1][c-1]);
	}

	public static boolean inbounds(int x, int y) {
		return x >= 0 && x < r && y >= 0 && y < c;
	}
}