import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set; public class Main { public static final int[][] move_dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public static boolean is_valid(int x, int y, int W, int H){ return x >= 0 && x < W && y >= 0 && y < H; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); final int W = sc.nextInt(); final int H = sc.nextInt(); int[][] heights = new int[H][W]; for(int i = 0; i < H; i++){ for(int j = 0; j < W; j++){ heights[i][j] = sc.nextInt(); } } LinkedList x_queue = new LinkedList(); LinkedList y_queue = new LinkedList(); LinkedList prev_queue = new LinkedList(); int[][][] minimum_cost = new int[10][H][W]; for(int i = 0; i < 10; i++){ for(int j = 0; j < H; j++){ for(int k = 0; k < W; k++){ minimum_cost[i][j][k] = Integer.MAX_VALUE; } } } minimum_cost[0][0][0] = 0; x_queue.add(0); y_queue.add(0); prev_queue.add(0); while(!x_queue.isEmpty()){ final int x = x_queue.poll(); final int y = y_queue.poll(); final int curr = heights[y][x]; final int prev = prev_queue.poll(); if(curr == prev){ continue; }else if(x == W - 1 && y == H - 1 && prev > 0){ System.out.println(minimum_cost[prev][y][x]); return; } //System.out.println(x + " " + y + " " + prev + " " + minimum_cost[prev][y][x]); for(final int[] move : move_dir){ final int nx = x + move[0]; final int ny = y + move[1]; if(!is_valid(nx, ny, W, H)){ continue; } final int next = heights[ny][nx]; if(prev == next){ continue; } final int next_cost = minimum_cost[prev][y][x] + 1; if(prev == 0 || prev < curr && curr > next || prev > curr && curr < next){ if(minimum_cost[curr][ny][nx] > next_cost){ minimum_cost[curr][ny][nx] = next_cost; x_queue.add(nx); y_queue.add(ny); prev_queue.add(curr); } } } } System.out.println(-1); } }