leetcode解题: Word Search (79)

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: DFS O(N^2) N是元素的个数

这题的思路是,对于一个给定的string, 他的起点可以在图中的任意位置,那么我们就必须要对每一个起点进行遍历。 对于任意一个遍历, 需要维护一个visited图,来记录已经访问过的节点。
对于每一个节点,有4个方向可以选择,对每一个方向进行探索,只要其中有一个方向能找到string, 那么就算找到了。
C++

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (word.empty()) {
return true;
}
if (board.empty() || board[0].empty()) {
return false;
}
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) {
bool temp = helper(word, board, visited, i, j);
if (temp) {
return true;
}
}
}
return false;
}
bool helper(string word, vector<vector<char>>& board, vector<vector<bool>>& visited, int row, int col) {
if (word.empty()) {
return true;
}
if (board[row][col] != word[0]) {
return false;
}
if (word.size() == 1) {
return true;
}
visited[row][col] = true;
string next = word.substr(1, word.size() - 1);
// check up
// bool up = false, right = false, bot = false, left = false;
if (row > 0 && !visited[row - 1][col] ) {
bool up = helper(next, board, visited, row - 1, col);
if (up) {
return true;
}
}
// right
if (col < board[0].size() - 1 && !visited[row][col + 1]) {
bool right = helper(next, board, visited, row, col + 1);
if (right) {
return true;
}
}
// down
if (row < board.size() - 1 && !visited[row + 1][col]) {
bool bot = helper(next, board, visited, row + 1, col);
if (bot) {
return true;
}
}
// left
if (col > 0 && !visited[row][col - 1]) {
bool left = helper(next, board, visited, row, col - 1);
if (left) {
return true;
}
}
visited[row][col] = false;
return false;
}
};

Java

1
2
<!--1-->