// Microsoft OA 51 LPA
// Find min distance between 2 and 3 in a grid with multiple 2 0 and 3
// Multisource BFS
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class PairInt {
int first;
int second;
public PairInt(int first, int second) {
this.first = first;
this.second = second;
}
}
public class Main {
public static void main
(String[] args
) {
Scanner scanner
= new Scanner
(System.
in);
int r = scanner.nextInt();
int c = scanner.nextInt();
int[][] grid = new int[r][c];
Queue<PairInt> queue = new LinkedList<>(); // we can also use ArrayDeque implementation but this is more common
boolean[][] seen = new boolean[r][c];
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
grid[i][j] = scanner.nextInt();
if(grid[i][j] == 2) {
queue.offer(new PairInt(i, j));
seen[i][j] = true;
}
}
}
int currLevel = 0;
int[] dirs = {-1, 0, 1, 0, -1};
while(!queue.isEmpty()) {
int levelSize = queue.size();
for(int i = 0; i < levelSize; i++) {
PairInt curr = queue.poll();
int currX = curr.first;
int currY = curr.second;
for(int j = 0; j < 4; j++) {
int newX = currX + dirs[j];
int newY = currY + dirs[j + 1];
if(newX >= 0 && newX < r && newY >= 0 && newY < c && !seen[newX][newY]) {
if(grid[newX][newY] == 0) {
queue.offer(new PairInt(newX, newY));
seen[newX][newY] = true;
} else if (grid[newX][newY] == 3) {
System.
out.
println(currLevel
+ 1); return;
}
}
}
}
currLevel++;
}
}
}