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.
方法1: dfs
思路:
首先遍历一遍找到词首字母,开始对上下左右dfs,寻找下一个字符。注意找到match 字符的位置需要被标记为visited,因为题目说同一位置的字符不能被用两次。
易错点
- 退出条件
- visited要用backtracking里的方式在退出之后恢复成false,给别的dfs机会再利用这个未知的字符。
Complexity
Time complexity: ?(?∗?∗4^ ?), where s is the length of the string, mn for for loop and for the dfs method its 4^ s. Since the dfs method goes only as deep as the word length we have T(k)=4(T(k-1))=4*4T(k-2)=…=… which will be 4^k.
Space complexity: O(mn), for visited matrix, 但是也有可能用一个特殊符号在原位标记visited,这样可以达到O(1)。space O(4mn) if the function call stack is taken into account. In each cell, we recursively call its 4four neighbors and there are mn cells in total.
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (board.empty() || board[0].empty()) return false;
int m = board.size();
int n = board[0].size();
vector<vector<bool>> visited(m, vector<bool> (n, false));
for (int i = 0 ; i < board.size(); i++){
for (int j = 0; j < board[0].size(); j++){
if (dfs(board, word, 0, visited, i, j)) return true;
}
}
return false;
}
bool dfs(vector<vector<char>> & board, string word, int start, vector<vector<bool>> & visited, int x, int y){
if (start == word.size()) return true;
if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || visited[x][y] || board[x][y] != word[start] ) return false;
visited[x][y] = true;
bool ret = dfs(board, word, start + 1, visited, x + 1, y)
|| dfs(board, word, start + 1, visited, x - 1, y)
|| dfs(board, word, start + 1, visited, x, y + 1)
|| dfs(board, word, start + 1, visited, x, y - 1);
visited[x][y] = false;
return ret;
}
};