class Solution { public: bool hasFun(char* matrix, int rows, int cols, char* str,int x,int y,bool * flags,int pos) { if(pos==strlen(str)) { return true; } if(x>=rows||y>=cols||x<0||y<0) return false; if(flags[x*cols+y]) return false; if(matrix[x*cols+y]==str[pos]) { flags[x*cols+y]=true; bool fc=hasFun(matrix,rows,cols,str,x-1,y,flags,pos+1)||hasFun(matrix,rows,cols,str,x+1,y,flags,pos+1)||hasFun(matrix,rows,cols,str,x,y-1,flags,pos+1)||hasFun(matrix,rows,cols,str,x,y+1,flags,pos+1); return fc; } else return false; } bool hasPath(char* matrix, int rows, int cols, char* str) { for(int x=0;x<rows;x++) { for(int y=0;y<cols;y++) { if(matrix[x*cols+y]==str[0]) { bool * flags=new bool[rows*cols]; for(int i=0;i<rows*cols;i++) { flags[i]=false; } if(hasFun(matrix,rows,cols,str,x,y,flags,0)) return true; } } } return false; } };