您的位置:首页 > 其它

广度优先遍历 之 LeetCode 542. 01 Matrix

2017-07-27 16:35 423 查看
  广度优先遍历是层序遍历的推广。层序遍历需要使用普通队列,因此,对于广度优先遍历,使用普通队列也是一个不错的选择。

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1:

Input:

0 0 0

0 1 0

0 0 0

Output:

0 0 0

0 1 0

0 0 0

Example 2:

Input:

0 0 0

0 1 0

1 1 1

Output:

0 0 0

0 1 0

1 2 1

Note:

The number of elements of the given matrix will not exceed 10,000.

There are at least one 0 in the given matrix.

The cells are adjacent in only four directions: up, down, left and right.

  基本思路:

  1. 初始化时,值为“0”的点置为0,其他点置为距离最大值。

  2. 以值为“0”的点为中心开始,向四周遍历。对于非“0”点,查看它上下左右四个点,其值为四个点的值中最小值+1。

  当要使用普通队列时,需要考虑每一轮需要将哪些对象入队,哪些不要入队。从而保证不要重复遍历。

public class Solution {
public int[][] updateMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;

//初始化,同时将第一轮遍历的对象——值为“0”的点入队
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
queue.offer(new int[] {i, j});
}
else {
matrix[i][j] = Integer.MAX_VALUE;
}
}
}

//表示左右下上四个位置的点
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

while (!queue.isEmpty()) {
int[] cell = queue.poll();//出队的元素作为此次遍历的中心点
for (int[] d : dirs) {
int r = cell[0] + d[0];
int c = cell[1] + d[1];
if (r < 0 || r >= m || c < 0 || c >= n ||
matrix[r][c] <= matrix[cell[0]][cell[1]] + 1) continue;//改行表示matrix[r][c]这个点已经是最优的了,即遍历过的了,因此不用再遍历了
queue.add(new int[] {r, c});将遍历过的点入队,作为下次遍历的中心点
matrix[r][c] = matrix[cell[0]][cell[1]] + 1;
}
}

return matrix;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息