1.单词搜索
这道题 使用回溯法的 深度优先搜索DFS
一般DFS都采用递归
那么如下代码中
flag存储的是这个元素是否被用过了
然后向上下左右四个方向来搜索
递归判断word的每一个字母即可
主函数的双for循环是来寻找单词的起点
class Solution {
public:
bool DFS(vector<vector<char>>& board, string word, int row, int col, int index, vector<vector<int>>& flag)
{
if(index==word.length())
{
return true;
}
if(row<0 || row>=board.size() || col<0 || col>=board[0].size() || board[row][col]!=word[index])
{
return false;
}
if(0==flag[row][col])
{
flag[row][col]=1;
if(DFS(board, word, row-1, col, index+1, flag))
{
return true;
}
if(DFS(board, word, row+1, col, index+1, flag))
{
return true;
}
if(DFS(board ,word, row, col-1, index+1, flag))
{
return true;
}
if(DFS(board, word, row, col+1, index+1, flag))
{
return true;
}
flag[row][col]=0;
}
return false;
}
bool exist(vector<vector<char>>& board, string word)
{
int m=board.size();
int n=board[0].size();
int k=word.length();
vector<vector<int>> flag(m,vector<int>(n,0));
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(DFS(board, word, i, j, 0, flag))
{
return true;
}
}
}
return false;
}
};