Word Search

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.

For example,

Given board =

1
2
3
4
5
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

word = “ABCCED”, -> returns true,

word = “SEE”, -> returns true,

word = “ABCB”, -> returns false.

回溯。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public:

typedef vector<int> vi;
typedef vector<vi> vvi;

vvi vis;
int index;
int* rdir;
int* cdir;
int rows;
int cols;
bool result;

void solve(vector<vector<char>>& board, int r, int c, string& word)
{

vis[r][c] = true;
if (word[index] == board[r][c])
{
if (result) return;
if (index == word.length() - 1) result = true;
for (int k = 0; k < 4; ++k)
{
int i = r - rdir[k];
int j = c - cdir[k];
if (i >= 0 && i < rows && j >= 0 && j < cols && vis[i][j] == 0)
{
++index;
solve(board, i, j, word);
--index;
}
}
}
vis[r][c] = false;
}

bool exist(vector<vector<char>>& board, string word) {
rows = board.size();
if (rows == 0) return false;
cols = board[0].size();
if (cols == 0) return false;
vis = vvi(rows, vi(cols, 0));
index = 0;
result = false;
int rdirs[] = { 0,0,1,-1 };
int cdirs[] = { 1,-1,0,0 };
rdir = rdirs;
cdir = cdirs;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
solve(board, i, j, word);
if (result) return true;
}
}
return false;
}
};