317. Shortest Distance from All Buildings https://www.youtube.com/watch?v=8K98WexA8m8 https://leetcode.com/problems/shortest-distance-from-all-buildings/discuss/76891/Java-solution-with-explanation-and-time-complexity-analysis Line 50: error: illegal start of type Idea: traverse from the buildings , use a 2d int array to keep track of the distance from all buildings to this empty land Also use another 2d int array to keep track of how many buildings have visited this place, The output is the one with shortest distance that can reach all buildings So we also use a var to count how many buildings in total class Solution { public int shortestDistance(int[][] grid) { int n = grid.length; int m = gird[0].length; int[][] distance = new int[n][m]; int[][] count = new int[n][m]; int numBui = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { bfs(grid, i, j, distance, count, n, m); numBui++; } } } } private void bfs(int[][] gird, int i, int j, int[][] distance, int[][] count, int n, int m) { int[][] directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; boolean[][] visited = new boolean[n][m]; Queue<int[]> queue = new LinkedList<>(); int level = 1; queue.offer(new int[]{i, j}); while (!queue.isEmpty()) { int size = queue.size(); for (int x = 0; x < size; x++) { int[] current = queue.poll(); for (int[] dir : directions) { int row = current[0] + dir[0]; int col = current[1] + dir[1]; if (row >= 0 && col >= 0 && row < n && col < m && grid[row][col] == 0 && visited[row][col] == false) { queue.offer(new int[]{row, col}); visited[row][col] = true; distance[row][col] += level; count[row][col] += 1; } } } level++; /////// level++ after visiting all the 0s on the same level } } int min = Integer.MAX_VALUE; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(grid[i][j] == 0 && count[i][j] == numBui){ min = Math.min(min, distance[i][j]); } } } return min == Integer.MAX_VALUE ? -1 : min; //// if doesn’t exists }
317. Shortest Distance from All Buildings
猜你喜欢
转载自www.cnblogs.com/tobeabetterpig/p/9451106.html
今日推荐
周排行