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.
Constraints:
board and word consists only of lowercase and uppercase English letters.
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
M, N = len(board), len(board[0])
dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def dfs(board, r, c, word, i):
if i == len(word): return True
if r < 0 or r == M or c < 0 or c == N or board[r][c] != word[i]: return False
tmp, board[r][c] = board[r][c], ''
for (dr, dc) in dirs:
if dfs(board, r + dr, c + dc, word, i + 1):
return True
board[r][c] = tmp
return False
for r in range(M):
for c in range(N):
if dfs(board, r, c, word, 0):
print(r, c)
return True
return False
/*
* @lc app=leetcode id=79 lang=cpp
*
* [79] Word Search
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> dirs{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
bool dfs(vector<vector<char>> &board, string &word, int pos, int i, int j, unordered_set<int> &visited) {
if (word[pos] != board[i][j]) return false;
for (const auto &d : dirs) {
int r = i + d[0], c = j + d[1];
if (r >= 0 && r < board.size() && c >= 0 && c < board[0].size() && !visited.count(r * board[0].size() + c)) {
visited.insert(r * board[0].size() + c);
if (dfs(board, word, pos + 1, r, c, visited)) return true;
visited.erase(r * board[0].size() + c);
}
}
return pos == word.size() - 1;
}
bool exist(vector<vector<char>>& board, string word) {
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
unordered_set<int> visited;
visited.insert(i * board[0].size() + j);
if (dfs(board, word, 0, i, j, visited)) return true;
}
}
return false;
}
};
// @lc code=end
class Solution {
int[][] dirs = new int[][]{{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
private boolean helper(char[][] board, String word, int index, int x, int y) {
if (index == word.length() - 1) {
if (word.charAt(index) == board[x][y]) {
return true;
} else {
return false;
}
} else if (board[x][y] != word.charAt(index)) {
return false;
}
board[x][y] ^= 256;
for (int[] dir : dirs) {
int nx = x + dir[0], ny = y + dir[1];
if (nx >= 0 && nx < board.length && ny >= 0 && ny < board[0].length) {
//System.out.println(Integer.toBinaryString(board[x][y]) + ", " + Integer.toBinaryString(256));
if (helper(board, word, index + 1, nx, ny)) {
return true;
}
//System.out.println(Integer.toBinaryString(board[x][y]));
}
}
board[x][y] ^= 256;
return false;
}
public boolean exist(char[][] board, String word) {
if (word.length() == 0) {
return true;
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (helper(board, word, 0, i, j)) {
return true;
}
}
}
return false;
}
}
Analysis
时间复杂度参照m_rao的分析"
I think the time complexity is (mn_4^k) where k is the length of the string; mn for for loop and for the dfs method its 4^k. 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."