import java.util.Arrays; import java.util.LinkedList; import java.util.Scanner; public class yukicoder123 { class Tuple { int x; int y; int[] his; Tuple(int x, int y, int[] his) { this.x = x; this.y = y; this.his = his; } boolean checkSequence(int c) { return isKadomatsuSequence(his[1], his[2], c); } @Override public String toString() { return "" + x + ":" + y + Arrays.toString(this.his); } } int[][] vec = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; boolean isKadomatsuSequence(int a, int b, int c) { if (a == c) { return false; } return (a - b) * (b - c) < 0; } int is(boolean b) { return b ? 1 : 0; } public yukicoder123() { Scanner scanner = new Scanner(System.in); int W = scanner.nextInt(); int H = scanner.nextInt(); int[][] matrix = new int[H][W]; int[][][][] checked = new int[H][W][10][2]; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { matrix[i][j] = scanner.nextInt(); for (int k = 0; k < 10; k++) { Arrays.fill(checked[i][j][k], Integer.MAX_VALUE); } } } LinkedList nextQueue = new LinkedList<>(); LinkedList queue = new LinkedList<>(); for (int i = 0; i < 10; i++) { Arrays.fill(checked[0][0][i], Integer.MAX_VALUE); } int start = matrix[0][0]; if (matrix[0][0] != matrix[0][1]) { int flag = is(matrix[0][0] > matrix[0][1]); checked[0][1][start][flag] = 1; queue.add(new Tuple(1, 0, new int[]{0, matrix[0][0], matrix[0][1]})); } if (matrix[0][0] != matrix[1][0]) { int flag = is(matrix[0][0] > matrix[1][0]); checked[1][0][start][flag] = 1; queue.add(new Tuple(0, 1, new int[]{0, matrix[0][0], matrix[1][0]})); } int turn = 2; boolean isGoal = false; MAIN: while (queue.size() > 0) { while (queue.size() > 0) { Tuple tuple = queue.pop(); for (int[] v : vec) { int x = tuple.x + v[0]; int y = tuple.y + v[1]; if (!(0 <= x && x < W && 0 <= y && y < H)) { continue; } if (!tuple.checkSequence(matrix[y][x])) { continue; } int flag = is(tuple.his[2] - matrix[y][x] > 0); if (checked[y][x][tuple.his[2]][flag] <= turn) { continue; } checked[y][x][tuple.his[2]][flag] = turn; if (y == H - 1 && x == W - 1) { isGoal = true; break MAIN; } nextQueue.add(new Tuple(x, y, new int[]{tuple.his[1], tuple.his[2], matrix[y][x]})); } } queue.addAll(nextQueue); nextQueue.clear(); turn++; } if (isGoal) { System.out.println(turn); } else { System.out.println(-1); } } public static void main(String[] args) { yukicoder123 hoge = new yukicoder123(); } }