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.
classSolution: 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 orr == Morc < 0 orc == Norboard[r][c] != word[i]: returnFalsetmp,board[r][c] = board[r][c], ''for (dr, dc) indirs:ifdfs(board, r + dr, c + dc, word, i +1): returnTrueboard[r][c] = tmpreturnFalseforrinrange(M):forcinrange(N):ifdfs(board, r, c, word,0):print(r, c)returnTruereturnFalse
/* * @lc app=leetcode id=79 lang=cpp * * [79] Word Search */// @lc code=startclassSolution {public: vector<vector<int>> dirs{{0,-1}, {0,1}, {-1,0}, {1,0}};booldfs(vector<vector<char>> &board,string&word,int pos,int i,int j,unordered_set<int> &visited) {if (word[pos] !=board[i][j]) returnfalse;for (constauto&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)) returntrue;visited.erase(r *board[0].size() + c); } }return pos ==word.size() -1; }boolexist(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)) returntrue; } }returnfalse; }};// @lc code=end
classSolution {int[][] dirs =newint[][]{{0,1}, {1,0}, {-1,0}, {0,-1}};privatebooleanhelper(char[][] board,String word,int index,int x,int y) {if (index ==word.length() -1) {if (word.charAt(index) == board[x][y]) {returntrue; } else {returnfalse; } } elseif (board[x][y] !=word.charAt(index)) {returnfalse; } 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)) {returntrue; }//System.out.println(Integer.toBinaryString(board[x][y])); } } board[x][y] ^=256;returnfalse; }publicbooleanexist(char[][] board,String word) {if (word.length() ==0) {returntrue; }for (int i =0; i <board.length; i++) {for (int j =0; j < board[0].length; j++) {if (helper(board, word,0, i, j)) {returntrue; } } }returnfalse; }}
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."