题解 | #矩阵中的路径#

矩阵中的路径

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


int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
bool find_flag =false;
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param matrix char字符型vector<vector<>>
     * @param word string字符串
     * @return bool布尔型
     */

    // const int maxsize =1000;
    void dfs(vector<vector<char> >& matrix,int x, int y, bool vis[1000][1000], int shape_x, int shape_y,string path,const string teststr) {
        if(path == teststr ){
            find_flag =true;
        }
        if (x >= 0 && x < shape_x && y >= 0 && y < shape_y
        &&!vis[x][y]&&teststr.substr(0,path.size())==path) {
            path.push_back(matrix[x][y]);
            vis[x][y] = true;

            cout<<path<<endl;
            for (int i = 0; i < 4; i++) {
                int next_x = x + dx[i];
                int next_y = y + dy[i];
                 
                dfs(matrix,next_x, next_y, vis, shape_x, shape_y,path,teststr);

            }
            vis[x][y ] = false;
            path.pop_back();
        }


        return ;
    }
    bool hasPath(vector<vector<char> >& matrix, string word) {
        // cout<<matrix.size()<<endl;
        // write code here
        bool    vis[1000][1000] = {false};

        for (int i = 0; i < matrix.size(); ++i) {
            for (int j = 0; j < matrix[i].size(); ++j) {
                dfs(matrix, i, j, vis, matrix.size(), matrix[i].size(),"",word);
            }
        }
        return find_flag? true:false;

    }
};

全部评论

相关推荐

群星之怒:不是哥们,你就不好奇瘫痪三十年的老植物人是啥样的吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务