【LeetCode】542. 01 Matrix
2017-05-27 19:04
435 查看
【LeetCode】542. 01 Matrix
【题目描述】
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.
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.
【输入输出】
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
【解题思路】
动态规划(DP):
1. ans[i][j] 存储到0的最少步数,flag记录上次循环是否有更新ans
2. 如果M[i][j] == 0, 则ans[i][j]=0; 否则为一步可达所有位置的ans最小值加一,即ans[i][j] = min(ans[i][j], 1+min(min((j > 0)?ans[i][j-1]:con, (j < col-1)?ans[i][j+1]:con), min((i > 0)?ans[i-1][j]:con, (i < row-1)?ans[i+1][j]:con)));
3. 返回ans
【代码】
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int row = matrix.size(), col = matrix[0].size(), flag = 1, con = 10001; vector<vector<int>> ans(row, vector<int>(col, con)); while(flag == 1) { flag = 0; for(int i = 0;i < row;i++) { for(int j = 0;j < col;j++) { int last = ans[i][j]; if(matrix[i][j] == 0) ans[i][j] = 0; else ans[i][j] = min(ans[i][j], 1+min(min((j > 0)?ans[i][j-1]:con, (j < col-1)?ans[i][j+1]:con), min((i > 0)?ans[i-1][j]:con, (i < row-1)?ans[i+1][j]:con))); if(ans[i][j] != last) flag = 1; } } } return ans; } };
相关文章推荐
- 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 距离0最近的距离 + 正反遍历 + 动态规划DP
- LeetCode 542. 01 Matrix
- LeetCode 542. 01 Matrix
- Leetcode-542. 01 Matrix
- LeetCode-542. 01 Matrix (JAVA)零一矩阵
- LeetCode 542----01 Matrix
- leetcode 542. 01 Matrix
- [LeetCode] 542. 01 Matrix
- leetcode 542. 01 Matrix
- LeetCode 542. 01 Matrix
- [LeetCode]542. 01 Matrix
- 第十五周:( LeetCode542) 01 Matrix(c++)
- 广度优先遍历 之 LeetCode 542. 01 Matrix
- 【LeetCode】542. 01 Matrix