牛客OJ:矩阵中的路径(DFS模版题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ShellDawn/article/details/88990429

需要注意的地方,字符串结尾作为dfs跳出会有bug,当字符串长度等于矩阵所有元素时。

#include <bits/stdc++.h>
using namespace std;

const int dirX[] = {-1,1,0,0};
const int dirY[] = {0,0,-1,1};
class Solution {
public:
    
    bool dfs(bool* flag,
        const char* m,const int r,const int c,
             const char* str,int i,int j,int loc){
        //printf("<%c %d %d %c>\n",m[i*c+j],i,j,str[loc]);
        if(str[loc] == 0) return true;
        if(str[loc] == m[i*c+j] && str[loc+1] == 0) return true;
        if(str[loc] != m[i*c+j]) return false;
        flag[i*c+j] = true;
        bool ans = false;
        for(int dir=0;dir<4;dir++){
            int newi = i + dirX[dir];
            int newj = j + dirY[dir];
            if(newi >= 0 && newi < r &&
              newj >= 0 && newj < c &&
              flag[newi*c+newj] == false){
                ans = ans || dfs(flag,m,r,c,str,newi,newj,loc+1);
            }
        }
        flag[i*c+j] = false;
        return ans;
    }
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if(strlen(str) <= 0) return true;
        bool ans = false;
        bool flag[rows*cols];
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                if(matrix[i*cols+j] == str[0]){
                    memset(flag,0,sizeof(flag));
                    ans = ans || dfs(flag,matrix,rows,cols,str,i,j,0);
                }
            }
        }
        return ans;
    }


};

int main(){
    Solution S;
    char a[] = "AAAAAAAAAAAA";
    char b[] = "AAAAAAAAAAAA";
    printf("%s\n",S.hasPath(a,3,4,b)?"YES":"NO");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ShellDawn/article/details/88990429