Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. class Solution:
  2.     def exist(self, board: List[List[str]], word: str) -> bool:
  3.         def isvalid(i,j):
  4.             return 0<=i<R and 0<=j<C
  5.         def helper(i,j,idx):
  6.             #print(i,j)
  7.             if idx == len(word):
  8.                 return True
  9.             for di, dj in [[-1,0],[0,1],[1,0],[0,-1]]:
  10.                 if isvalid(i+di,j+dj) and not visited[i+di][j+dj] and board[i+di][j+dj] == word[idx]:
  11.                     visited[i][j]=1
  12.                     if helper(i+di,j+dj,idx+1):
  13.                         return True
  14.                     visited[i][j]=0
  15.        
  16.         self.flag = False          
  17.         R = len(board)
  18.         C= len(board[0])
  19.         visited = [[0]*C for _ in range(R)]
  20.         start = []
  21.         for i in range(R):
  22.             for j in range(C):
  23.                 if board[i][j] == word[0]:
  24.                     start.append((i,j))
  25.                    
  26.         for i,j in start:
  27.             visited[i][j]=1
  28.             if helper(i,j,1):
  29.                 return True
  30.             visited[i][j]=0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement