25/06/2021

[Java] Find word in matrix

Given a matrix of characters and a word, find if the word appears in the matrix. Words can be searched in the matrix only going left to right or top to bottom, but NOT mixing them.

Example

c a r

a r d

r f d

Word = car can be found either in first row or first column but NOT in 'ca' from first row + 'r' from next row.

We can run a loop on each character in the matrix and if we find a match for the first character of the string, we start two searches:

  • rest of the row
  • rest of the column

to see if we find a match for the word.

Assuming our word has length S, our complexity is O(MNS) as for each cell in the matrix we do at most S work.

You can check my implementation of wordSearchLRTB on my Gist along with some tests in WordSearchLRTBJTests.

No comments:

Post a Comment

With great power comes great responsibility