542. 01 Matrix [LeetCode]
2017-07-21 22:50
615 查看
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:
Output:
Example 2:
Input:
Output:
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.
题目大意:这题给我们一个0-1矩阵,要我们求出矩阵中每个元素,到最近的0的距离。
思路概述:因为0元素最后的返回值还是0,要求元素1到最近的0的距离,首先就想到BFS。首先,我从每一个1开始向周围BFS,直到找到最近的0,但这样做的时间复杂度过高,提交结果TLE,没有能够通过。
之后在LeetCode的讨论区学习了一下,发现思路没有什么问题,只是BFS遍历时可以优化一下:遍历原数组,将1都置为Max_Value。建立一个队列,加入所有0元素的位置;之后从队列中的元素出发遍历周边元素,如果其周边的元素不越界且大于元素值+1,更新其值为当前中心元素值+1,将这个周边元素加到队列中,构成下一层节点。
AC代码如下:
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.
题目大意:这题给我们一个0-1矩阵,要我们求出矩阵中每个元素,到最近的0的距离。
思路概述:因为0元素最后的返回值还是0,要求元素1到最近的0的距离,首先就想到BFS。首先,我从每一个1开始向周围BFS,直到找到最近的0,但这样做的时间复杂度过高,提交结果TLE,没有能够通过。
之后在LeetCode的讨论区学习了一下,发现思路没有什么问题,只是BFS遍历时可以优化一下:遍历原数组,将1都置为Max_Value。建立一个队列,加入所有0元素的位置;之后从队列中的元素出发遍历周边元素,如果其周边的元素不越界且大于元素值+1,更新其值为当前中心元素值+1,将这个周边元素加到队列中,构成下一层节点。
AC代码如下:
public class Solution { public int[][] updateMatrix(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; if (m==0 || n==0 || matrix==null) return null; 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[] dir : dirs) { int x = cell[0] + dir[0]; int y = cell[1] + dir[1]; if (x<0 || x>=m || y<0 || y>=n || matrix[x][y] <= matrix[cell[0]][cell[1]]+1) continue; queue.offer(new int[] {x, y}); matrix[x][y] = matrix[cell[0]][cell[1]] + 1; } } return matrix; } }
相关文章推荐
- [Leetcode] #542 01 Matrix (BFS)
- [leetcode]542. 01 Matrix
- leetcode-542-01 Matrix
- Leetcode 542. 01 Matrix(BFS)
- [算法分析与设计] leetcode 每周一题: 542. 01 Matrix
- leetcode 542. 01 Matrix
- [leetcode]-542 01 Matrix
- 【leetcode】542. 01 Matrix的解法总结
- LeetCode 542. 01 Matrix
- [Leetcode] 542. 01 Matrix 解题报告
- Leetcode-542. 01 Matrix
- LeetCode-542. 01 Matrix (JAVA)零一矩阵
- leetcode 542. 01 Matrix 距离0最近的距离 + 正反遍历 + 动态规划DP
- LeetCode 542----01 Matrix
- LeetCode 542. 01 Matrix
- [LeetCode] 542. 01 Matrix
- leetcode 542. 01 Matrix
- 广度优先遍历 之 LeetCode 542. 01 Matrix
- LeetCode 542. 01 Matrix
- [LeetCode]542. 01 Matrix