Description: The distance between two adjacent cells is 1. Example 1: Input: Output: Solution: 思路使用bfs不是很难,主要是有点抽象。
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
[[0,0,0],
[0,1,0],
[0,0,0]]
[[0,0,0],
[0,1,0],
[0,0,0]]
public int[][] updateMatrix(int[][] matrix) { Queue<Integer[]> bfs = new LinkedList<>(); int dist = 0; int m = matrix.length, n = matrix[0].length; for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[i].length; j++){ if(matrix[i][j] == 0) bfs.offer(new Integer[]{i, j}); // keep track of all 0's else matrix[i][j] = Integer.MAX_VALUE; // else initialize distance to infinity } } int[][] directions = {{1,0}, {-1, 0}, {0, 1}, {0, -1}}; while(!bfs.isEmpty()){ Integer[] current = bfs.poll(); for(int[] d : directions){ int i = current[0] + d[0]; int j = current[1] + d[1]; // if new cell is out of bounds or is already closer to another 0, stop further bfs in this cell if(i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] <= matrix[current[0]][current[1]] + 1) continue; bfs.offer(new Integer[] {i, j}); // put in queue for further bfs operations matrix[i][j] = matrix[current[0]][current[1]] + 1; // update new smaller distance } } return matrix; }
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算