Shortest Distance from All Buildings

class Solution {
		public int shortestDistance(int[][] grid) {
			if (grid == null || grid.length == 0 || grid[0].length == 0) return -1;
			int count = 0;
		for (int i = 0; i < grid.length; i++) {
				for (int j = 0; j < grid[0].length; j++) {
			if (grid[i][j] == 1) {
				count++;	
			}
		}	
			}
		
			int ans = Integer.MAX_VALUE;
			for (int i = 0; i < grid.length; i++) {
				for (int j = 0; j < grid[0].length; j++) {
			if (grid[i][j] == 0) {
		ans = Math.min(ans, bfs(grid, i, j, count));
			}
		}
			}
			return ans == Integer.MAX_VALUE ? -1 : ans;
		}
		
		private int bfs(int[][] grid, int x, int y, int count) {
			boolean[][] visited = new boolean[grid.length][grid[0].length];
			Queue<Integer> qx = new LinkedList<>();
			Queue<Integer> qy = new LinkedList<>();
		
			int[] dx = {1, -1, 0, 0};
			int[] dy = {0, 0, 1, -1};
			
			visited[x][y] = true;
			qx.offer(x);
			qy.offer(y);
			int step = 0;
			int sum = 0;
			while (!qx.isEmpty()) {
				step++;
				int size = qx.size();
				for (int i = 0; i < size; i++ ) {
					int cx = qx.poll();
					int cy = qy.poll();
					for (int k = 0; k < 4; k++) {
						int nx = cx + dx[k];
						int ny = cy + dy[k];
						if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && !visited[nx][ny] && count != 0) {
							visited[nx][ny] = true;
							if (grid[nx][ny] == 1) {
								count--;
								sum += step;
							} else if (grid[nx][ny] == 0) {
								qx.offer(nx);
								qy.offer(ny);
							}
						}
					}
				}
			}
			return count == 0 ? sum : Integer.MAX_VALUE;
		}
}

最后更新于

这有帮助吗?