publicintsnakesAndLadders(int[][] board) { if (board[0][0] != -1) return -1; n = board.length; nums = newint[n * n + 1]; booleanflag=true; for (inti= n - 1, index = 1; i >= 0; --i) { for (intj= flag ? 0 : n - 1; flag ? j < n : j >= 0; j += flag ? 1 : -1) { nums[index++] = board[i][j]; } flag = !flag; } return bfs(); }
privateintbfs() { Deque<Integer> queue = newArrayDeque<>(); Map<Integer, Integer> map = newHashMap<>(); queue.offer(1); map.put(1, 0); while (!queue.isEmpty()) { intcur= queue.poll(); intstep= map.get(cur); if (cur == n * n) return step; for (inti=1; i <= 6; ++i) { intni= cur + i; if (ni <= 0 || ni > n * n) continue; if (nums[ni] != -1) ni = nums[ni]; if (map.containsKey(ni)) continue; map.put(ni, step + 1); queue.offer(ni); } } return -1; } }