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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Shortest Distance from All Buildings

發布時間:2025/4/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Shortest Distance from All Buildings 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Shortest Distance from All Buildings

題目鏈接:https://leetcode.com/problems...

這道題要求最短的距離,一般這種要求可以到的地方的距離,都需要把整個圖遍歷一遍,遍歷一般就是bfs和dfs。這道題不用dfs的原因是:empty的位置到building的距離是按最小值來算的,用dfs每次如果放入depth不一定是最小的距離,每次都得更新,沒有效率。這道題用bfs的原因:一樣的原因,因為距離就是按照最小的距離來算的,完全是bfs的思路。
visited一般兩種方式:用一個boolean的矩陣,直接改寫grid的值。這里用第二種。-grid[i] [j]表示(i, j)點可以reach到的building數目。當grid[i] [j] == # of buildings so far時,證明當前點還沒被visited,且當前點被之前所有的buildings都visited過,那么每次bfs只訪問這些點。如果該point沒有被之前所有的buildings訪問過,就不可能成為答案(根據要求empty的位置能到所有的buildings),其他與它相鄰的點也是這樣。和用boolean矩陣比,縮小了每次遍歷的范圍。
從每一個building,即grid[i] [j] == 1的點開始做bfs層次遍歷。

  • 用一個distance矩陣來記錄(i, j)到所有building的距離和,對每一個building做bfs

  • 每次bfs的時候,更新distance[i] [j]的值:

    • Queue<int[]> 記錄point

    • 更新level += 1

    • go over當前level的全部point

      • if (i, j)在圖內&grid[i] [j] = -num:

        • distance[i] [j] += level

        • grid[i] [j] --

        • q.offer(i, j)

  • go over整個distance數組,當-grid[i] [j] == # of buildings時,更新最小的距離值

  • public class Solution {public int shortestDistance(int[][] grid) {/* approach: bfs, distance array* for each building, do a bfs, add the distance* variable: num: record number of buildings already searched* visited => use the grid => do -- if visited[i][j] = -num* result: the grid[i][j] == -(number of buildings) is the possible* find the smallest distance[i][j]*/distance = new int[grid.length][grid[0].length];int num = 0;for(int i = 0; i < grid.length; i++) {for(int j = 0; j < grid[0].length; j++) {if(grid[i][j] == 1) {bfs(grid, i, j, -num);num++;}}}int result = Integer.MAX_VALUE;// find the smallest distancefor(int i = 0; i < grid.length; i++) {for(int j = 0; j < grid[0].length; j++) {if(grid[i][j] == -num) result = Math.min(result, distance[i][j]);}}return result == Integer.MAX_VALUE ? -1 : result;}int[][] distance;int[] dx = new int[] {-1, 1, 0, 0};int[] dy = new int[] {0, 0, -1, 1};private void bfs(int[][] grid, int x, int y, int num) {Queue<int[]> q = new LinkedList();q.offer(new int[] {x, y});int len = 0;while(!q.isEmpty()) {len++;// current levelfor(int j = q.size(); j > 0; j--) {int[] cur = q.poll();// 4 directionsfor(int i = 0; i < 4; i++) {int nx = cur[0] + dx[i], ny = cur[1] + dy[i];if(nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == num) {distance[nx][ny] += len;q.offer(new int[] {nx, ny});grid[nx][ny]--;}}}}} }

    總結

    以上是生活随笔為你收集整理的Shortest Distance from All Buildings的全部內容,希望文章能夠幫你解決所遇到的問題。

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