leetcode:0-1 矩阵问题

//DFS (Time Limited)
class Solution {
public:
    int dfs(vector<vector<int>> &matrix,int i,int j,int R,int C,bool** visited){
        int res=R+C;

        if (0==matrix[i][j]) return 0;

        visited[i][j]=true;

        if (j>0&&!visited[i][j-1]){//left
            res=min(res,1+dfs(matrix,i,j-1,R,C,visited));
        }
        if (j1&&!visited[i][j+1]){//right
            res=min(res,1+dfs(matrix,i,j+1,R,C,visited));
        }
        if (i>0&&!visited[i-1][j]){//up
            res=min(res,1+dfs(matrix,i-1,j,R,C,visited));
        }
        if (i1&&!visited[i+1][j]){//down
             res=min(res,1+dfs(matrix,i+1,j,R,C,visited));
        }

        visited[i][j]=false;

        return res;
    }

    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int R=matrix.size(),C=matrix[0].size();
        vector<vector<int>> ret(R,vector<int>(C,0));

        bool **visited=new bool *[R];
        for (int i=0;inew bool [C];
           fill(visited[i],visited[i]+C,false);
        }

        for (int i=0;ifor (int j=0;jdelete [] visited;
        return ret;
    }
};
//BFS
class Solution {
public:
    //BFS 只进入合法节点
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int R=matrix.size(),C=matrix[0].size();
        queueint,int>> q;
        vectorint,int>> adjust={{0,-1},{0,1},{-1,0},{1,0}};
        for (int i=0;ifor (int j=0;jif (0==matrix[i][j]) q.push({i,j});
                else matrix[i][j]=INT_MAX;
            }
        }

        while(!q.empty()){
            pair<int,int> coordinate=q.front();
            q.pop();

            int i=coordinate.first,j=coordinate.second;

            for (auto d:adjust){

                auto x=i+d.first,y=j+d.second;
                if(x>=0 && x=0 && yif (matrix[x][y]>=matrix[i][j]+1){//careful
                        matrix[x][y]=1+matrix[i][j];
                        q.push({x,y});
                    } 
                }
            }
        }
        return matrix;
    }
};

你可能感兴趣的:(c++算法)