https://leetcode.com/problems/word-search/description/
example
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
solution
深搜,对目标字符串每一位,在棋盘中进行搜索
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size(), n = board[0].size(); // height and width
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(board[i][j] == word[0]) // 合法的起始点
{
vector<vector<bool> > vis(m, vector<bool>(n, false));
vis[i][j] = true;
if(word.length() == 1) // 只有一个字符的情况
return true;
if(dfs(i, j, 1, board, word, vis) == true)
{
return true;
}
}
}
}
return false;
}
// 现在处于棋盘的(x, y)位置,要搜索字符串的第 i 位
bool dfs(int x, int y, int ind, vector<vector<char>> board, string word, vector<vector<bool> > vis)
{
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int m = vis.size(), n = vis[0].size();
for(int i=0;i<4;i++)
{
int newx = x+dx[i], newy = y+dy[i];
if(newx>=m || newx<0 || newy>=n || newy<0 || vis[newx][newy] == true)
continue;
if(board[newx][newy] == word[ind]) // 这一位符合条件
{
if(ind == word.length()-1) // 所有位都已经找到
return true;
vis[newx][newy] = true;
if(dfs(newx, newy, ind+1, board, word, vis) == true) // 继续找下一位
return true;
else
{
vis[newx][newy] = false;
continue;
}
}
}
return false;
}
};