leetcode 1293. Shortest Path in a Grid with Obstacles Elimination | 1293. 网格中的最短路径(BFS)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 1293. Shortest Path in a Grid with Obstacles Elimination | 1293. 网格中的最短路径(BFS)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
題解
DFS 遞歸超時,看了評論區 & 答案區,沒有可運行的 DFS 解法,這題只能 BFS。疑問:DFS 的復雜度是多少?
嘗試改成帶緩存的遞歸,但是由于 visited 數組的存在,當前狀態還與整個 visited 表有關,dfs(x, y, k) 三個參數不足以表示當前狀態,無法加緩存,除非將 visited 數組也當做緩存的一個維度。
嘗試用 dp[x][y][k] 剪枝優化,如果已經遇到過 dp[x][y][k],且之前的 k 大于當前的 k,則剪枝,此優化幾乎無效果。
總結:帶有visited數組的回溯是一種有后效性的遞歸,無法轉換成dp.
BFS 參考:Java-Straightforward-BFS-O(MNK)-time-or-O(MNK)-space
方法1:DFS(TLE)
本地測過幾個例子,代碼應該沒問題。
class Solution {int M;int N;public int shortestPath(int[][] grid, int k) {M = grid.length;N = grid[0].length;boolean[][] visited = new boolean[M][N];k = grid[0][0] == 1 ? k - 1 : k;int res = bfs(0, 0, 0, k, grid, visited);System.out.println(res);return res == Integer.MAX_VALUE ? -1 : res;}// at position (x,y), remain k obstacles to remove// if valid, return min stepspublic int bfs(int steps, int x, int y, int k, int[][] grid, boolean[][] visited) {if (x < 0 || x >= M || y < 0 || y >= N || visited[x][y] || k < 0) return Integer.MAX_VALUE;if (x == M - 1 && y == N - 1) return steps;int t = grid[x][y] == 0 ? k : k - 1;visited[x][y] = true;int p1 = bfs(steps + 1, x, y - 1, t, grid, visited);int p2 = bfs(steps + 1, x, y + 1, t, grid, visited);int p3 = bfs(steps + 1, x - 1, y, t, grid, visited);int p4 = bfs(steps + 1, x + 1, y, t, grid, visited);visited[x][y] = false;return Math.min(Math.min(p1, p2), Math.min(p3, p4));} }方法2:BFS(AC)
class Solution {int M;int N;int[][] ways = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};public int shortestPath(int[][] grid, int k) {M = grid.length;N = grid[0].length;Queue<int[]> queue = new LinkedList<>();boolean[][][] visited = new boolean[M][N][k + 1];visited[0][0][0] = true;queue.offer(new int[]{0, 0, 0});int step = 0;while (!queue.isEmpty()) {int size = queue.size();for (int i = 0; i < size; i++) {int[] record = queue.poll();int x = record[0];int y = record[1];int curK = record[2];if (x == M - 1 && y == N - 1) return step;for (int[] way : ways) { // 4個方向int nextX = x + way[0];int nextY = y + way[1];int nextK = curK;if (nextX >= 0 && nextX < M && nextY >= 0 && nextY < N) {if (grid[nextX][nextY] == 1) nextK++;if (nextK <= k && !visited[nextX][nextY][nextK]) {visited[nextX][nextY][nextK] = true;queue.offer(new int[]{nextX, nextY, nextK});}}}}step++;}return -1;} }總結
以上是生活随笔為你收集整理的leetcode 1293. Shortest Path in a Grid with Obstacles Elimination | 1293. 网格中的最短路径(BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 526. Beauti
- 下一篇: leetcode 467. Unique