Advertisement
Aikiro42

Word Search using Recursion

Jan 29th, 2020
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1.  
  2. r, c = map(int, input().split())
  3. grid = [input() for _ in range(r)]
  4. n = int(input())
  5. words = [input() for _ in range(n)]
  6. word_coors = {}
  7.  
  8.  
  9. '''
  10. grid = ['xatnysnprabvbas', 'teehsdaerpslyug', 'soqgknsscoklpsn', 'ochmacaeceteeei', 'fyasarnprrrhfak']
  11. r, c = len(grid), len(grid[0])
  12. words = ['bar', 'engine', 'key', 'networking', 'save', 'scan', 'scanner', 'screen', 'screenshot',
  13.             'script', 'scroll', 'search', 'security', 'server', 'shareware', 'shell', 'shift', 'snapshot',
  14.             'social', 'software', 'spam', 'spammer', 'spreadsheet', 'spyware', 'status', 'storage',
  15.             'supercomputer', 'surf', 'syntax']
  16. word_coors = {}
  17. '''
  18.  
  19. # 0: right, rotation cc
  20. direction = [
  21.     (1, 0),
  22.     (1, 1),
  23.     (0, 1),
  24.     (-1, 1),
  25.     (-1, 0),
  26.     (-1, -1),
  27.     (0, -1),
  28.     (1, -1)
  29. ]
  30.  
  31.  
  32. def search_direction(x, y, d, w, i=0):
  33.     if grid[y][x] == w[i]:
  34.         if len(word) - 1 == i:
  35.             return True
  36.         else:
  37.             x += direction[d][0]
  38.             y += direction[d][1]
  39.             if 0 <= x < c and 0 <= y < r:
  40.                 i += 1
  41.                 if i < len(word):
  42.                     return search_direction(x, y, d, w, i)
  43.                 else:
  44.                     return False
  45.             else:
  46.                 return False
  47.     else:
  48.         return False
  49.  
  50.  
  51. def search_cell(x, y, word):
  52.     search = [search_direction(x, y, d, word) for d in range(8)]
  53.     if True in search:
  54.         return True
  55.     else:
  56.         return False
  57.  
  58.  
  59. for word in words:
  60.     for y in range(r):
  61.         for x in range(c):
  62.             if word[0] == grid[y][x]:
  63.                 if search_cell(x, y, word) and word not in word_coors:
  64.                     word_coors[word] = (y+1, x+1)
  65.  
  66. for word in words:
  67.     print(*word_coors[word])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement