题解 | #矩阵中的路径#

矩阵中的路径

http://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6

简单的dfs,做一下简单的判断即可,记得引用传参

class Solution {
public:
    vector<vector<bool>> search_map_;
    int row_;
    int col_;
    bool is_success_ = false;//
    void DFS(vector<vector<char> >& matrix,int x,int y,int cur,const string& word){
        if(is_success_)return;
        if(x >= row_||y >= col_ || x<0 || y<0 ){// limit
            return;
        }
        if(search_map_[x][y]== true || word[cur] != matrix[x][y]){
            // current char is not right or searched
            return;
        }
        if(cur == word.size()-1){// the last char
            is_success_ = true;
            return;
        }
        search_map_[x][y]=true;
        DFS(matrix,x+1,y,cur+1,word);
        DFS(matrix,x-1,y,cur+1,word);
        DFS(matrix,x,y+1,cur+1,word);
        DFS(matrix,x,y-1,cur+1,word);
        search_map_[x][y]=false; // reset search item
    }

    bool hasPath(vector<vector<char> >& matrix, string word) {
        if(matrix.empty()||word.empty()){
            return false;
        }
        row_ = matrix.size();
        col_  = matrix[0].size();
        for(int i=0;i<row_;i++){
            search_map_.push_back(vector<bool>(col_,false));
        }
        for(int i=0;i<row_;i++){
            for(int j=0;j<col_;j++){
                if(matrix[i][j] == word[0]){
                    DFS(matrix,i,j,0,word);
                    if(is_success_){
                        return true;
                    }
                }
            }
        }
        return false;
    }
};
全部评论

相关推荐

抱抱碍事梨a:三点建议,第一点是建议再做一个项目,把自我介绍部分顶了,第二点是中南大学加黑加粗,第三点是建议加v详细交流
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务