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.
publicclassLC79WordSearch {publicbooleanexist(char[][] board,String word) {if (board ==null||board.length==0|| board[0].length==0|| word ==null||word.length() ==0) returntrue;int rows =board.length;int cols = board[0].length;for (int r =0; r < rows; r++) {for (int c =0; c < cols; c++) {// scan board, start with word first character if (board[r][c] ==word.charAt(0)) {if (helper(board, word, r, c,0)) {returntrue; } } } }returnfalse; }privatebooleanhelper(char[][] board,String word,int r,int c,int start) {// already match word all characters, return trueif (start ==word.length()) returntrue;if (!isValid(board, r, c)|| board[r][c] !=word.charAt(start)) returnfalse;// mark visited board[r][c] ='*';boolean res =helper(board, word, r +1, c, start +1)||helper(board, word, r, c +1, start +1)||helper(board, word, r -1, c, start +1)||helper(board, word, r, c -1, start +1);// backtracking to start position board[r][c] =word.charAt(start);return res; }privatebooleanisValid(char[][] board,int r,int c) {return r >=0&& r <board.length&& c >=0&& c < board[0].length; }}
Python3 Code
classSolution:defexist(self,board: List[List[str]],word:str) ->bool: m =len(board) n =len(board[0])defdfs(board,r,c,word,index):if index ==len(word):returnTrueif r <0or r >= m or c <0or c >= n or board[r][c] != word[index]:returnFalse board[r][c] ='*' res = dfs(board, r - 1, c, word, index + 1) or dfs(board, r + 1, c, word, index + 1) or dfs(board, r, c - 1, word, index + 1) or dfs(board, r, c + 1, word, index + 1)
board[r][c] = word[index]return resfor r inrange(m):for c inrange(n):if board[r][c] == word[0]:ifdfs(board, r, c, word, 0):returnTrue