542. 01 Matrix

来源:互联网 发布:opencv python视频教程 编辑:程序博客网 时间:2024/05/29 19:07

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

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.

本题给出一个01矩阵,要求求出矩阵中的1到最近的0的距离
一开始我用动态规划的思想递归求解min( min( dis(le), dis(ri)), min( dis(up), dis(dn) ) ) +1,但是发现在递归过程中,发现在求dis(le)的时候会用到原来的点的距离,导致程序出错。后来想到找出矩阵中值为0的点,从这些点开始用BFS方式把距离“扩散”出去,不为0的点则从周围4点取最小值加1。由于之前扩散过的点在发现新的值为0的点后可能会有更小的距离,所以我们使用两次扩散,一次从矩阵左上角开始,一次从右下角。详细代码如下:
class Solution {public:    #define IMAX INT_MAX    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {        vector<int> temp;        vector<vector<int> > res;        if(matrix.size() == 0)  return res;        for(int i = 0; i < matrix[0].size(); i++)            temp.push_back(IMAX);        for(int i = 0; i < matrix.size(); i++)            res.push_back(temp);        for(int i = 0; i < matrix.size(); i++)        {            for(int j = 0; j < matrix[i].size(); j++)            {                if(matrix[i][j] == 0) res[i][j] = 0;                else                {                    if(i && res[i-1][j] != IMAX && res[i-1][j] < res[i][j])                        res[i][j] = res[i-1][j] + 1;                    if(j && res[i][j-1] != IMAX && res[i][j-1] < res[i][j])                        res[i][j] = res[i][j-1] + 1;                    if(i < matrix.size() - 1 && res[i+1][j] != IMAX && res[i+1][j] < res[i][j])                        res[i][j] = res[i+1][j] + 1;                    if(j < matrix[i].size() - 1 && res[i][j+1] != IMAX && res[i][j+1] < res[i][j])                        res[i][j] = res[i][j+1] + 1;                }            }        }        for(int i = matrix.size() - 1; i >= 0; i--)        {            for(int j = matrix[i].size() - 1; j >= 0; j--)            {                if(matrix[i][j] == 0) res[i][j] = 0;                else                {                    if(i && res[i-1][j] != IMAX && res[i-1][j] < res[i][j])                        res[i][j] = res[i-1][j] + 1;                    if(j && res[i][j-1] != IMAX && res[i][j-1] < res[i][j])                        res[i][j] = res[i][j-1] + 1;                    if(i < matrix.size() - 1 && res[i+1][j] != IMAX && res[i+1][j] < res[i][j])                        res[i][j] = res[i+1][j] + 1;                    if(j < matrix[i].size() - 1 && res[i][j+1] != IMAX && res[i][j+1] < res[i][j])                        res[i][j] = res[i][j+1] + 1;                }            }        }        return res;    }};


原创粉丝点击