542. 01 矩阵

题目:

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

示例 1:
输入:

0 0 0
0 1 0
0 0 0
输出:

0 0 0
0 1 0
0 0 0
示例 2:
输入:

0 0 0
0 1 0
1 1 1
输出:

0 0 0
0 1 0
1 2 1
注意:

给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。

 

解答:

多源BFS:从多个0同步开始BFS。

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int m=matrix.size(),n=matrix[0].size();
        vector<vector<int>> res(m,vector<int>(n,INT_MAX));
        vector<vector<int>> dif={{0,1},{0,-1},{1,0},{-1,0}};
        queue<pair<int,int>> que;
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                if(matrix[i][j]==0){
                    que.push({i,j});
                    res[i][j]=0;
                }
            }
        }
        int distance=0;
        while(not que.empty()){
            int len=que.size();
            while(len>0){
                auto cur=que.front();
                que.pop();
                for(int i=0;i<4;++i){
                    int new_x=cur.first+dif[i][0],new_y=cur.second+dif[i][1];
                    if(new_x>=0 and new_x<m and new_y>=0 and new_y<n and res[new_x][new_y]==INT_MAX){
                        que.push({new_x,new_y});
                        res[new_x][new_y]=(matrix[new_x][new_y]==0)?0:distance+1;
                    }
                }
                --len;
            }
            ++distance;
        }
        return move(res);
    }
};

 

动态规划:

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int m=matrix.size(),n=matrix[0].size();
        vector<vector<int>> res(m,vector<int>(n,10000));
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                if(matrix[i][j]==0){
                    res[i][j]=0;
                }
                else{
                    if(i-1>=0){
                        res[i][j]=min(res[i-1][j]+1,res[i][j]);
                    }
                    if(j-1>=0){
                        res[i][j]=min(res[i][j-1]+1,res[i][j]);
                    }
                }
            }
        }
        for(int i=m-1;i>=0;--i){
            for(int j=n-1;j>=0;--j){
                if(res[i][j]==0){
                    continue;
                }
                else{
                    if(i+1<m){
                        res[i][j]=min(res[i+1][j]+1,res[i][j]);
                    }
                    if(j+1<n){
                        res[i][j]=min(res[i][j+1]+1,res[i][j]);
                    }
                }
            }
        }
        return move(res);
    }
};

 

posted @ 2020-04-23 02:37  NeoZy  阅读(171)  评论(0)    收藏  举报