广度优先遍历 之 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。
当要使用普通队列时,需要考虑每一轮需要将哪些对象入队,哪些不要入队。从而保证不要重复遍历。
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; } }
相关文章推荐
- 01 Matrix--广度优先遍历bfs--leetcode
- leetcode 542. 01 Matrix 距离0最近的距离 + 正反遍历 + 动态规划DP
- [LeetCode]542. 01 Matrix
- [算法分析与设计] leetcode 每周一题: 542. 01 Matrix
- 第十五周:( LeetCode542) 01 Matrix(c++)
- leetcode 542. 01 Matrix
- [Leetcode] #542 01 Matrix (BFS)
- Leetcode 542. 01 Matrix(BFS)
- leetcode - 637. Average of Levels in Binary Tree【广度优先遍历 + 辅助变量】
- leetcode 542. 01 Matrix
- LeetCode | 515. Find Largest Value in Each Tree Row 广度优先遍历
- 【广度优先遍历】leetcode - Word Ladder II
- 【leetcode】542. 01 Matrix的解法总结
- LeetCode Binary Tree Right Side View : 思想上的基于队列的广度优先遍历,形式上的一个简单变种
- leetcode - 662. Maximum Width of Binary Tree【广度优先遍历 + 层次计数】
- leetcode-542-01 Matrix
- Leetcode - 广度优先遍历
- leetcode 515. Find Largest Value in Each Tree Row 二叉树每一层最大值+广度优先遍历BFS
- Leetcode 之BFS广度优先遍历
- LeetCode 542. 01 Matrix