12. 矩阵中的路径

class Solution {
public:
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    bool st[5][5];
    bool dfs(vector<vector<char>>& matrix,int i,int j,int u,string &str)
    {
        if(u==str.size())
            return true;
        for (int k = 0; k < 4; k ++ )
        {
            int x=dx[k]+i,y=dy[k]+j;
            if(x<0||x>=matrix.size()||y<0||y>=matrix[x].size())
                continue;
            if(st[x][y]||matrix[x][y]!=str[u])  continue;
            if(dfs(matrix,x,y,u+1,str))    return true;
        }
        return false;
    }
    bool hasPath(vector<vector<char>>& matrix, string &str) {
        if(!matrix.size()||!matrix[0].size())    return false;

        for (int i = 0; i < matrix.size(); i ++ )
            for (int j = 0; j < matrix[i].size(); j ++ )
                if(str[0]==matrix[i][j]&&!st[i][j])
                {
                    st[i][j]=true;
                    if(dfs(matrix,i,j,1,str))
                        return true;
                    st[i][j]=false;
                }

        return false;
    }
};
posted @ 2023-03-17 20:43  穿过雾的阴霾  阅读(15)  评论(0)    收藏  举报