I was asked this interview question on recursion & backtracking the other day and have not found a feasible solution, here is the question:
Given a grid and a word, write a function that returns the location of the word in the grid as a list of coordinates. If there are multiple matches, return any one.
grid1 = [
['c','c','x','t','i','b'],
['c','c','a','t','n','i'],
['a','c','n','n','t','t'],
['t','c','s','i','p','t'],
['a','o','o','o','a','a'],
['o','a','a','a','o','o'],
['k','a','i','c','k','i']
]
word1 = 'catnip'
word2 = 'cccc'
word3 = 's'
word4 = 'bit'
word5 = 'aoi'
word6 = 'ki'
word7 = 'aaa'
word8 = 'ooo'
grid2 = [
['a']
]
word9 = 'a'
The desired solutions are shown below:
find_word_location(grid1, word1) => [(1,1), (1,2),(1,3),(2,3),(3,3),(3,4)]
find_word_location(grid1, word2) =>
[(0,1),(1,1),(2,1),(3,1)]
OR [(0,0),(1,0),(1,1),(2,1)]
OR [(0,0),(0,1),(1,1),(2,1)]
OR [(1,0),(1,1),(2,1),(3,1)]
find_word_location(grid1,word3) => [(3,2)]
find_word_location(grid1,word4) => [(0,5),(1,5),(2,5)]
find_word_location(grid1,word5) => [(4,5),(5,5),(6,5)]
find_word_location(grid1,word6) => [(6,4),(6,5)]
find_word_location(grid1,word7) => [(5,1),(5,2),(5,3)]
find_word_location(grid1,word8) => [(4,1),(4,2),(4,3)]
find_word_location(grid2,word9) => [(0,0)]
I was also asked about the complexity analysis with the following variables:
r = number of rows
c = number of columns
w = length of the word
It would also be wise to mention that only letters either to the right or below the letter being evaluated are considered, if those letters do not correspond to the next letter in the word there must be some backtracking process that occurs.
I have a Python function but it does not produce the desired output:
coords = []
width = len(grid[0]) # 6
height = len(grid) # 7
def find_word(i , row, col):
if i == len(word):
return True
if word[i] == grid[row][col]:
coords.append((row, col))
if col + 1 < width and find_word( i + 1,row, col + 1):
return True
elif row + 1 < height and find_word(i+1, row+1, col):
return True
coords.pop() # neither the right or below element provided the next character in word
return False
if col + 1< width and find_word(i, row,col+1):
return True
elif row +1 < height and find_word(i, row+1, 0):
return True
i = 0 # the word index
row = 0 # row index
col = 0 # column index
find_word(0, 0, 0)
Any help would be much appreciated.