日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 286. 墙与门 多源BFS和DFS

發布時間:2023/12/13 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 286. 墙与门 多源BFS和DFS 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?思路1: DFS,對于每個門進行一次DFS搜索,記錄每個位置對每個門的距離,當有更小距離的門時更新這個數值

public void WallsAndGates(int[][] rooms) {for (int i = 0; i < rooms.GetLength(0); i++){for (int j = 0; j < rooms[i].GetLength(0); j++){if (rooms[i][j] == 0){DFS(rooms, i, j, 0);}}} }void DFS(int[][] rooms, int x, int y, int val){if (x < 0 || x >= rooms.GetLength(0))return;if (y < 0 || y >= rooms[x].GetLength(0))return;if (rooms[x][y] < val)return;rooms[x][y] = val;DFS(rooms, x + 1, y, val + 1);DFS(rooms, x, y + 1, val + 1);DFS(rooms, x - 1, y, val + 1);DFS(rooms, x, y - 1, val + 1);}

?思路2: 多源BFS,先把每個門都壓入隊列中,然后進行BFS搜索,BFS搜索保證了每個位置只需要遍歷到一次,第一次搜索到時一定是最短距離,因此這種算法對于大量數據時肯定會更優秀

private List<int[]> directions = new List<int[]>(){new int[]{1, 0}, new int[]{-1, 0},new int[]{0, 1},new int[]{0, -1}}; private const int INF = 2147483647; public void WallsAndGates(int[][] rooms){Queue<int[]> queue = new Queue<int[]>();int?maxRow?=?rooms.GetLength(0);if(maxRow == 0)return;int?maxCow?=?rooms[0].Length;for (int i = 0; i < maxRow; i++){for (int j = 0; j < maxCow; j++){if (rooms[i][j] == 0){queue.Enqueue(new int[]{i,j});}}}while(queue.Count > 0){int[] tile = queue.Dequeue();for(int i = 0; i < directions.Count; i++){int x = tile[0] + directions[i][0];int y = tile[1] + directions[i][1];if(x < 0 || x > maxRow - 1 || y < 0 || y > maxCow - 1 || rooms[x][y] != INF){continue;}rooms[x][y] = rooms[tile[0]][tile[1]] + 1;queue.Enqueue(new int[]{x, y});}} } }

判題的結果是兩者時間差不多太多,都在340ms左右,但是明顯在數據量大的情況下應該是多源BFS算法更優秀很多。多源BFS最快是328ms,第一次的704ms是因為用了List沒有Queue

?

總結

以上是生活随笔為你收集整理的LeetCode 286. 墙与门 多源BFS和DFS的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。