单词搜索,迷宫问题中 进行了边界限制
代码如下`(下面代码测试用例都可以通过,时间上面超过了,没想明白)
class Solution {
//这个其实就是加了一些剪枝的限制,因该说更好写了
private:
int arr[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool isArea( int temp_i,int temp_j,vector<vector<char>> board)
{
if(temp_i>=0&&temp_i<=board.size()-1&&temp_j>=0&&temp_j<=board[0].size()-1){return true;}
return false;
}
bool _exist(vector<vector<char>>& board,string &word,vector<vector<bool>> &used,int &index,int start_i,int start_j)
{
if(index==word.size())//一定要注意这里。
{
return board[start_i][start_j]==word[word.size()-1];
}
for(int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
int temp_i=start_i+arr[i][0];
int temp_j=start_j+arr[i][1];
//首先判断是不是在网格内,然后判断是不是未访问,然后看是不是等于下一个字母, 在网格内,没有访问,等于下一个字母,就递归
if(isArea(temp_i,temp_j,board)&&used[temp_i][temp_j]==false&&board[temp_i][temp_j]==word[index])
{
cout<<word[index]<<endl;
used[temp_i][temp_j]=true;
index++;
if(_exist( board,word,used,index, temp_i, temp_j)==true)
{
return true;
}
index--;
used[temp_i][temp_j]=false;
}
}
return false;
}
public:
bool exist(vector<vector<char>>& board, string word)
{
int index=1;
vector<vector<bool>> used(board.size(),vector<bool>(board[0].size(),false));
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[0].size();j++)
{
if(board[i][j]==word[0])
{
used[i][j]=true;
if(_exist( board, word, used,index, i, j)==true)
{
return true;
}
used[i][j]=false;
}
}
}
return false;
}
};