您的位置:首页 > 其它

【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