很容易就想到回溯
cpp
class Solution {
private:
int istrue = false;
int dir[4][2] = { -1,0,0,-1,0,1,1,0 };
void backtracking(vector<vector<char>>& board, string word, vector<vector<bool>>& visited, int x, int y, int index)
{
if (index == word.size())//当找全word的字母,则标记
{
istrue = true;
return;
}
for (int i = 0; i < 4; i++)
{
int nextx = x + dir[i][0];
int nexty = y + dir[i][1];
if (nextx >= board.size() || nexty >= board[0].size() || nextx < 0 || nexty < 0)
continue;
if (visited[nextx][nexty] == false && board[nextx][nexty] == word[index])
{
visited[nextx][nexty] = true;
backtracking(board, word, visited, nextx, nexty, index + 1);
visited[nextx][nexty] = false;//回溯
}
}
}
public:
bool exist(vector<vector<char>>& board, string word) {
vector<vector<bool>>visited(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++)
{
//遍历所有字母,找到word中第一个字母,再进行深度优先搜索找word的其他字母
if (board[i][j] == word[0])
{
visited[i][j] = true;
backtracking(board, word, visited, i, j, 1);
visited[i][j] = false;//回溯
//一旦找到,直接返回
if(istrue)
return true;
}
}
}
return istrue;
}
};