class Solution { public boolean exist(char[][] board, String word) { for(int i=0; i<board.length; i++) { for(int j=0; j<board[0].length; j++) { if(exist(board, i, j, word, 0)) return true; } } return false; } public boolean exist(char[][] board, int x, int y, String word, int index) { if(index == word.length()) return true; if(x < 0 || y<0 || x>=board.length || y>=board[0].length || board[x][y] != word.charAt(index)) return false; board[x][y] ^= 128; boolean exist = exist(board, x-1, y, word, index+1) || exist(board, x+1, y, word, index+1) || exist(board, x, y-1, word, index+1) || exist(board, x, y+1, word, index+1) ; board[x][y] ^= 128; return exist; } }
补充一个python的实现:
1 class Solution: 2 def dfs(self,board,word,index,rows,coloums,visited,i,j): 3 if index >= len(word): 4 return True 5 if i >= rows or i < 0 or j >= coloums or j < 0 or visited[i][j] == 1 or board[i][j] != word[index]: 6 return False 7 visited[i][j] = 1 8 result = self.dfs(board,word,index+1,rows,coloums,visited,i+1,j) or self.dfs(board,word,index+1,rows,coloums,visited,i-1,j) or self.dfs(board,word,index+1,rows,coloums,visited,i,j+1) or self.dfs(board,word,index+1,rows,coloums,visited,i,j-1) 9 10 visited[i][j] = 0 11 12 return result 13 14 def exist(self, board: 'List[List[str]]', word: 'str') -> 'bool': 15 rows = len(board) 16 coloums = len(board[0]) 17 visited = [[0 for a in range(coloums)] for b in range(rows)] 18 for i in range(rows): 19 for j in range(coloums): 20 if self.dfs(board,word,0,rows,coloums,visited,i,j): 21 return True 22 return False