Leetcode-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.

Constraints:

  • board and word consists only of lowercase and uppercase English letters.
  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • 1 <= word.length <= 10^3

Example 1

1
2
3
4
5
6
7
8
9
10
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.

解题思路

回溯法。尝试从每个位置开始,合成单词。每个位置有上下左右四个选择,若当前选择无法合成单词,做下一个选择。若当前选择合成单词成功,直接返回。

复杂度分析

  • 时间复杂度:$O(nm^4)$,总共有 n 个位置,单词的长度为 m。每个字母最多要经过四次选择。
  • 空间复杂度:$O(m)$,用于存储单词合成的中间结果。

代码

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
class Solution {
vector<vector<int>> dirs = { {-1,0},{0,-1},{1,0},{0,1} };
public:
bool exist(vector<vector<char>>& board, string word) {
string rword(word.rbegin(), word.rend() - 1);
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
if (board[i][j] == word[0]) {
board[i][j] = '.';
if (search(board, rword, i, j)) return true;
board[i][j] = word[0];
}
}
}
return false;
}

private:
bool search(vector<vector<char>> &board, string &word, int i, int j) {
if (word.size() == 0) return true;
char c = word.back();
for (auto &d : dirs) {
if (isValid(board, c, i + d[0], j + d[1])) {
board[i + d[0]][j + d[1]] = '.';
word.pop_back();
if (search(board, word, i + d[0], j + d[1])) return true;
word.push_back(c);
board[i + d[0]][j + d[1]] = c;
}
}
return false;
}

bool isValid(vector<vector<char>> &board, char c, int i, int j) {
if (i >= 0 && i < board.size() && j >= 0 && j < board[0].size())
return board[i][j] == c;
return false;
}
};