Re: [閒聊] 每日LeetCode

看板Marginalman作者 (みけねこ的鼻屎)時間3年前 (2022/11/21 23:21), 編輯推噓8(802)
留言10則, 8人參與, 3年前最新討論串112/719 (看更多)
1926. Nearest Exit from Entrance in Maze 龍大被困在邊板了,總是忍不住偷看邊板,龍大想要從邊板逃出去他必須要走過一個迷宮 而且走太慢會被邊板仔抓回來,所以龍大要走最短的路線逃走,求出龍大逃出邊板這個 迷宮最短需要走幾步(逃不出去就返回-1)。 +:牆壁不能走 .:道路 Example: https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2] Output: 1 Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3]. Initially, you are at the entrance cell [1,2]. - You can reach [1,0] by moving 2 steps left. - You can reach [0,2] by moving 1 step up. It is impossible to reach [2,3] from the entrance. Thus, the nearest exit is [0,2], which is 1 step away. 思路: 1.一開始用DFS找出口吃了TLE,因為這題是要求最短路徑所以用BFS效率比較好,不用 算出所有的路線(BFS只要找到任意一個出口,該出口必定是最短出口) 2.一開始先把入口設定成牆壁(不能從迷宮入口回走,龍大會回到邊板) 3.然後從起點的上下左右出發用queue來跑BFS,紀錄移動後的座標{X, Y, 距離} 如果遇到邊界表示碰到一個出口,如果這個出口不是起點就返回我們已經走的距離。 4.放入Queue的條件是下個點的位置不是牆壁,我們要把每個走過的地方都標記成牆壁 避免回頭走。 JavaCode: --------------------------------------- class Solution { public int nearestExit(char[][] maze, int[] entrance) { int[][] directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int m = maze.length; int n = maze[0].length; int ey = entrance[0]; int ex = entrance[1]; maze[ey][ex] = '+'; Queue<int[]> queue = new LinkedList<>(); queue.offer(new int[] {ey, ex, 0}); while (!queue.isEmpty()) { int[] curr = queue.poll(); for (int[] direction : directions) { int py = curr[0] + direction[0]; int px = curr[1] + direction[1]; if (px < 0 || py < 0 || px >= n || py >= m) { if (curr[0] == ey && curr[1] == ex) continue; return curr[2]; } if (maze[py][px] == '.') { queue.offer(new int[]{py, px, curr[2] + 1}); maze[py][px] = '+'; } } } return -1; } } --------------------------------------- https://i.imgur.com/acHi4CL.png
-- https://i.imgur.com/uiFto42.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.111.108 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1669044104.A.ECE.html

11/21 23:23, 3年前 , 1F
靠北
11/21 23:23, 1F

11/21 23:25, 3年前 , 2F
@d*******
11/21 23:25, 2F

11/21 23:25, 3年前 , 3F
大師
11/21 23:25, 3F

11/21 23:27, 3年前 , 4F
BFS
11/21 23:27, 4F

11/21 23:41, 3年前 , 5F
大師
11/21 23:41, 5F

11/22 01:30, 3年前 , 6F
大師
11/22 01:30, 6F

11/22 03:04, 3年前 , 7F
大師
11/22 03:04, 7F

11/22 15:30, 3年前 , 8F
同樣邏輯但 Python 還是 TLE,哭啊
11/22 15:30, 8F

11/22 16:09, 3年前 , 9F
哦沒有,我把現在的點設為牆壁的時間點跟你不一樣,修改後
11/22 16:09, 9F

11/22 16:09, 3年前 , 10F
就可以了,哭啊
11/22 16:09, 10F
文章代碼(AID): #1ZUvU8xE (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZUvU8xE (Marginalman)