Advertisement
Guest User

Untitled

a guest
Jul 19th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. def get_moves(pos,board):
  2.     rows = len(board)
  3.     cols = len(board[0])
  4.     i,j = pos
  5.     moves = []
  6.     if j-1>=0:
  7.         left = (i,j-1)
  8.         moves.append(left)
  9.     if i-1>=0:
  10.         up = (i-1,j)
  11.         moves.append(up)
  12.     if i+1<(rows):
  13.         down = (i+1,j)
  14.         moves.append(down)
  15.     if j+1<(cols):
  16.         right = (i,j+1)
  17.         moves.append(right)
  18.     if i-1>=0 and j-1>=0:
  19.         top_left = (i-1,j-1)
  20.         moves.append(top_left)
  21.     if i+1<rows and j-1>=0:
  22.         down_left = (i+1,j-1)
  23.         moves.append(down_left)
  24.     if i-1>=0 and j+1<cols:
  25.         top_right = (i-1,j+1)
  26.         moves.append(top_right)
  27.     if i+1<rows and j+1<(cols):
  28.         down_right = (i+1,j+1)
  29.         moves.append(down_right)
  30.     return moves
  31.  
  32.  
  33.  
  34.  
  35.  
  36. def dfs(word,board):
  37.     start = 0
  38.     stack = []
  39.     rows = len(board)
  40.     cols = len(board[0])
  41.     for i in range(rows):
  42.         for j in range(cols):
  43.             if board[i][j] == word[start]:
  44.                 s = set()
  45.                 s.add((i,j))
  46.                 stack.append(((i,j),s,1))
  47.     while stack:
  48.         (i,j), visited,count = stack.pop()
  49.         print(i,j,count,word[count-1])
  50.         if count == len(word):
  51.             return True
  52.         moves = get_moves((i,j),board)
  53.         for (new_i,new_j) in moves:
  54.             print(new_i,new_j)
  55.             if (new_i,new_j) not in visited and board[new_i][new_j] == word[count]:
  56.                 visited.add((new_i,new_j))
  57.                 stack.append(((new_i,new_j),set(visited),count+1))
  58.                 visited.remove((new_i,new_j))
  59.     return False
  60.  
  61.  
  62.  
  63.  
  64. def wordBoggle(board, words):
  65.     rows = len(board)
  66.     cols = len(board[0])
  67.     ans = []
  68.     words.sort()
  69.     for word in words:
  70.         if dfs(word,board):
  71.             ans.append(word)
  72.  
  73.     return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement