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.
思路
只需要寻找是否有解,不需要最优解。因此可以采用DFS(深度优先遍历)的方法。
以board上的每个cell为出发点,利用depth first search向上下左右四个方向搜索匹配word。
注意点:
- board的边界
- cell是否已经在DFS的路径上被用过
- cell上的值是否与word的当前字符匹配
C++11
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (board.empty()) return false;
int m = board.size(), n = board[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
for (auto i = 0; i < m; ++i)
for (auto j = 0; j < n; ++j)
if (searchWord(board, visited, i, j, word, 0)) return true;
return false;
}
bool searchWord(vector<vector<char>>& board, vector<vector<bool>>& visited, int i, int j, string word, int index) {
if (index == word.size()) return true;
int m = board.size(), n = board[0].size();
if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || board[i][j] != word[index])
return false;
visited[i][j] = true; //搜索到该点,设置已访问
bool res = searchWord(board, visited, i + 1, j, word, index + 1)
|| searchWord(board, visited, i - 1, j, word, index + 1)
|| searchWord(board, visited, i, j + 1, word, index + 1)
|| searchWord(board, visited, i, j - 1, word, index + 1);
visited[i][j] = false; //重新设置成未访问,因为它有可能出现在下一次搜索的别的路径中
return res;
}
};