题目大意:给你一个字符矩阵和一个单词,判断是否矩阵中有一条路径为这个单词,数据大小写敏感。
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
最直接的办法为深搜,有点像那个找迷宫出口或者迷宫中两个点的最短路径的办法
AC代码如下
class Solution {
public:
bool map[1000][1000];
bool find(vector<vector<char> > &borad,string word,bool map[][1000],int x,int y,int z,int right,int buttom)
{
if(map[x][y]==true)return false;
if(borad[x][y]==word[z])
{
if(z==word.length()-1)
return true;
map[x][y]=true;
if(y>0)if(find(borad,word,map,x,y-1,z+1,right,buttom))return true;
if(y<right-1)if(find(borad,word,map,x,y+1,z+1,right,buttom))return true;
if(x>0)if(find(borad,word,map,x-1,y,z+1,right,buttom))return true;
if(x<buttom-1)if(find(borad,word,map,x+1,y,z+1,right,buttom))return true;
map[x][y]=false;
return false;
}else
return false;
}
bool exist(vector<vector<char> > &board, string word) {
int m=board.size();
if(m==0)return false;
int n=board[0].size();
if(n==0)return false;
memset(map,false,sizeof(map));
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(find(board,word,map,i,j,0,n,m))return true;
}
}
return false;
}
};
其实这里面的map我想用动态二维数组的,但是会有RT的错误。
RT代码如下:
class Solution {
public:
bool find(vector<vector<char> > &borad,string &word,bool **map,int x,int y,int z,int right,int buttom)
{
if(map[x][y]==true)return false;
if(z>=word.length())return false;
if(borad[x][y]==word[z])
{
if(z==word.length()-1)
return true;
map[x][y]=true;
if(y>0)if(find(borad,word,map,x,y-1,z+1,right,buttom))return true;
if(y<right-1)if(find(borad,word,map,x,y+1,z+1,right,buttom))return true;
if(x>0)if(find(borad,word,map,x-1,y,z+1,right,buttom))return true;
if(x<buttom-1)if(find(borad,word,map,x+1,y,z+1,right,buttom))return true;
map[x][y]=false;
return false;
}else
return false;
}
bool exist(vector<vector<char> > &board, string word) {
int m=board.size();
if(m==0)return false;
int n=board[0].size();
if(n==0)return false;
bool **map=(bool **)malloc(sizeof(bool *)*m);
for(int i=0;i<m;i++)
map[i]=(bool *)malloc(sizeof(bool)*n);
memset(map,false,sizeof(map));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
if(find(board,word,map,i,j,0,n,m))return true;
return false;
}
};
如果您看出哪里错了请不吝赐教!小弟万分感谢