Advertisement
jinhuang1102

79. Word Search

Nov 6th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. class Solution:
  2.     def dfs(self, word, board, x, y, visited):      
  3.         if board[x][y] != word[0]:
  4.             return False
  5.        
  6.         if not word[1:]:
  7.             return True
  8.        
  9.         dx = [0, -1, 0, 1]
  10.         dy = [-1, 0, 1, 0]
  11.        
  12.         for i in range(4):
  13.             rx, ry = x + dx[i], y + dy[i]
  14.             if rx < 0 or ry < 0 or rx > len(board) - 1 or ry > len(board[0]) - 1:
  15.                 continue
  16.             elif [rx, ry] in visited:
  17.                 continue
  18.             else:
  19.                 visited.append([x, y])
  20.                 res = self.dfs(word[1:], board, rx, ry, visited)
  21.                 if res is True:
  22.                     return res
  23.                 else:
  24.                     visited.pop()
  25.                
  26.         return False
  27.                
  28.    
  29.    
  30.     def exist(self, board, word):
  31.         """
  32.        :type board: List[List[str]]
  33.        :type word: str
  34.        :rtype: bool
  35.        """
  36.         if not board or not board[0]:
  37.             return False
  38.        
  39.         m = len(board)
  40.         n = len(board[0])
  41.        
  42.         for i in range(m):
  43.             for j in range(n):
  44.                 res = self.dfs(word, board, i, j, [])
  45.                 if res is True:
  46.                     return res
  47.                
  48.         return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement