79. Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
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.
Approach
- 这道题也是比较经典的递归回溯题,从一个矩阵中是否能拼凑成
word
,然后每个字母只能用一次,所以很明显需要记录它的轨迹,我们开辟一个轨迹vis
,然后我们递归查找它的四个方向,上下左右,走过的地方要标记,然后假如有一个方向找到了,那么直接返回,如果所有方向都查找不到,将此时的标记的抹去,因为不确定是否会在其他轨迹用到这个字母。16ms - 发现多次调用size()方法,会减低速度,所以让其变成全局变量了。
Code
class Solution {
public:
int N, M, wordlen;
bool exist(vector<vector<char>>& board, string word) {
if (board.size() == 0)return false;
vector<vector<int>>dir{ {0,0,1,-1},{1,-1,0,0} };
N = board.size(), M = board[0].size(), wordlen = word.size();
vector<vector<int>>vis(N, vector<int>(M, false));
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (board[i][j] == word[0]){
vis[i][j] = true;
if (FindWordInBoard(dir, board, vis, string(1, board[i][j]), word, i, j, 1)) {
return true;
}
else {
vis[i][j] = false;
}
}
}
}
return false;
}
bool FindWordInBoard(vector<vector<int>>&dir,vector<vector<char>>& board,vector<vector<int>>&vis,string cur,string &word,int x,int y,int pos) {
if (pos == wordlen) {
return true;
}
for (int i = 0; i < 4; i++) {
int newx = x + dir[0][i];
int newy = y + dir[1][i];
if (newx<0 || newy<0 || newx>N - 1 || newy>M - 1)continue;
if (!vis[newx][newy]&&board[newx][newy] == word[pos]) {
vis[newx][newy] = true;
if (FindWordInBoard(dir, board, vis, cur, word, newx, newy, pos + 1)) {
return true;
}
else {
vis[newx][newy] = false;
}
}
}
return false;
}
};