Leetcode word search
DFS。
AC的代码
class Solution {
public:
bool flag;
bool used[250][250];
bool exist(vector<vector<char> > &board, string word)
{
if(word=="")return true;
int m=board.size();
if(m==0)return false;
int n=board[0].size();
flag=false;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
used[i][j]=false;
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(!flag)dfs(0,i,j,board,word);
}
}
return flag;
}
void dfs(int depth,int x,int y,vector<vector<char> > &board, string word)
{
if(flag)return;
if(depth==word.size())
{
flag=true;
return;
}
if(x<0||y<0||x>=board.size()||y>=board[0].size())
return;
if(used[x][y])return;
if(board[x][y]==word[depth])
{
used[x][y]=true;
dfs(depth+1,x,y+1,board,word);
dfs(depth+1,x+1,y,board,word);
dfs(depth+1,x-1,y,board,word);
dfs(depth+1,x,y-1,board,word);
used[x][y]=false;
}
}
};
导致部分答案WA的代码:
void dfs(int depth,int x,int y,vector<vector<char> > &board, string word)
{
if(x<0||y<0||x>=board.size()||y>=board[0].size())
return;
if(depth==word.size())
{
flag=true;
return;
}
if(used[x][y])return;
if(board[x][y]==word[depth])
{
used[x][y]=true;
dfs(depth+1,x,y+1,board,word);
dfs(depth+1,x+1,y,board,word);
dfs(depth+1,x-1,y,board,word);
dfs(depth+1,x,y-1,board,word);
used[x][y]=false;
}
}
以上代码同样导致judge large时TLE,原因是重复搜索超时。
浙公网安备 33010602011771号