package no124; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { static int[] di = {1,0,-1,0}; static int[] dj = {0,1,0,-1}; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int w = sc.nextInt(); int h = sc.nextInt(); int[][] map = new int[h][w]; for(int i=0;i= h || nj < 0 || nj >= w) { continue; } if (isKasomatsuSequence(bef, map[i][j], map[ni][nj])) { g.addEdge(i + j * h + bef * h * w, ni + nj * h + map[i][j] * h * w, 1); } } } } } int[] dist = g.minDistQueue(0); int ans = Graph.INF; for(int i=0;i<=9;i++) { ans = Math.min(ans, dist[h-1 + (w-1) * h + i * h * w]); } if (ans == Graph.INF) { System.out.println(-1); }else{ System.out.println(ans); } } public static boolean isKasomatsuSequence(int a,int b,int c) { if (a == 0) { return true; } if (a == b || a == c || b == c) { return false; } return b < a && b < c || b > a && b > c; } } class Graph { public static final int INF = 1<<29; int n; ArrayList[] graph; @SuppressWarnings("unchecked") public Graph(int n) { this.n = n; this.graph = new ArrayList[n]; for(int i=0;i(); } } public void addBidirectionalEdge(int from,int to,int cost) { addEdge(from,to,cost); addEdge(to,from,cost); } public void addEdge(int from,int to,int cost) { graph[from].add(new Edge(to, cost)); } //O(E) all cost is 0 or 1 public int[] minDistQueue(int s) { int[] d = new int[n]; Arrays.fill(d, INF); ArrayDeque q = new ArrayDeque(); q.add(s); d[s] = 0; while(!q.isEmpty()) { int v = q.pollFirst(); for(Edge e:graph[v]) { int u = e.to; if (d[v] + e.cost < d[u]) { d[u] = d[v] + e.cost; if (e.cost == 0) { q.addFirst(u); }else{ q.addLast(u); } } } } return d; } class Edge { int to; int cost; public Edge(int to,int cost) { this.to = to; this.cost = cost; } } }