【LeetCode】542. 01 Matrix

来源:互联网 发布:本地系统 网络受限 编辑:程序博客网 时间:2024/06/13 02:35

【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:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.


【输入输出】

Example 1: 
Input:

0 0 00 1 00 0 0
Output:
0 0 00 1 00 0 0

Example 2: 
Input:

0 0 00 1 01 1 1
Output:
0 0 00 1 01 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;    }};