Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find words in matrix of letters

This is another question I was asked in the telephonic interview:

Given a dictionary and a crossword(2d matrix of characters) find all the dictionary words which can be found in the crossword.

All I could think of was hash the dictionary, find every possible word in the crossword and search the hash. I could not optimize it all.

Must admit Microsoft interview questions are tough :(

Please give me the lines to think on.

like image 409
Edward Avatar asked Nov 30 '10 12:11

Edward


People also ask

How do I find a word in a matrix Python?

I would re-write your search() function to take two arguments --- a matrix and a target. Then you can call it with the initial matrix, and the transposed matrix. I'd also modify the search() function to search each row forwards and backwards (and I might make that last part optional).


1 Answers

How about:

  • build a search tree for the dictionary (one level per letter)
  • for each position in the grid, start searching through the index, one character at a time, and proceed in each allowed direction until there are no entries left in the index, or you hit a grid boundary

I don't think a hash would be a very useful optimization here.

like image 89
tdammers Avatar answered Sep 30 '22 21:09

tdammers