Advertisement
Byleth_CYY

Untitled

May 15th, 2020
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. class Solution:
  2. """
  3. @param board: A list of lists of character
  4. @param word: A string
  5. @return: A boolean
  6. """
  7. def exist(self, board, word):
  8. # write your code here
  9. self.m,self.n=len(board),len(board[0])
  10. self.visited=[[0]*self.n for _ in range(self.m)]
  11. self.direction=[[0,1],[1,0],[0,-1],[-1,0]]
  12.  
  13. #find out starting point:
  14. for i in range(self.m):
  15. for j in range(self.n):
  16. if board[i][j]==word[0] and self.findPath(i,j,board,word,1):
  17. return True
  18. self.visited=[[0]*self.n for _ in range(self.m)]
  19. return False
  20.  
  21. def findPath(self,i,j,board,word,index):
  22. if index==len(word):
  23. return True
  24.  
  25. if self.visited[i][j]=1:
  26. return False
  27.  
  28. self.visited[i][j]=1
  29. for direct in self.direction:
  30. x,y=i+direct[0],j+direct[1]
  31. if 0<=x<self.m and 0<=y<self.n and self.visited[x][y]==0 and board[x][y]==word[index]:
  32. print(board[x][y])
  33.  
  34. self.findPath(x,y,board,word,index+1)
  35. self.visited[i][j]=0
  36. return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement