909. 蛇梯棋
题目:
思路:
【1】广度优先搜索
代码展示:
【1】广度优先搜索
//时间4 ms 击败 69.78% //内存42.3 MB 击败 49.22% class Solution { public int snakesAndLadders(int[][] board) { int n = board.length; boolean[] vis = new boolean[n * n + 1]; Queue<int[]> queue = new LinkedList<int[]>(); queue.offer(new int[]{1, 0}); while (!queue.isEmpty()) { int[] p = queue.poll(); for (int i = 1; i <= 6; ++i) { int nxt = p[0] + i; if (nxt > n * n) { // 超出边界 break; } int[] rc = id2rc(nxt, n); // 得到下一步的行列 if (board[rc[0]][rc[1]] > 0) { // 存在蛇或梯子 nxt = board[rc[0]][rc[1]]; } if (nxt == n * n) { // 到达终点 return p[1] + 1; } if (!vis[nxt]) { vis[nxt] = true; queue.offer(new int[]{nxt, p[1] + 1}); // 扩展新状态 } } } return -1; } public int[] id2rc(int id, int n) { int r = (id - 1) / n, c = (id - 1) % n; if (r % 2 == 1) { c = n - 1 - c; } return new int[]{n - 1 - r, c}; } } //时间3 ms 击败 93.46% //内存42.1 MB 击败 60.13% class Solution { public int snakesAndLadders(int[][] board) { int n = board.length; int[] arr = new int[n * n + 1]; int cnt = 1; for(int i = n - 1; i >= 0; i--) { if((n - 1 - i) % 2 == 0) { for(int j = 0; j < n; j++) { arr[cnt++] = board[i][j]; } }else { for(int j = n - 1; j >= 0; j--) { arr[cnt++] = board[i][j]; } } } int step = 0; int[] vis = new int[n * n + 1]; Queue<Integer> queue = new LinkedList<>(); queue.offer(1); vis[1] = 1; while(!queue.isEmpty()) { step++; int size = queue.size(); for(int i = 0; i < size; i++) { int start = queue.poll(); for(int j = 1; j <= 6; j++) { if(start + j > n * n) { break; } int end = start + j; if(arr[end] != -1) end = arr[end]; if(vis[end] != 0) continue; queue.offer(end); vis[end] = 1; } if(vis[n * n] == 1) { return step; } } } return -1; } }