Given a 2D grid m*n of characters and a word, find all occurrences of the given word in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match in this direction (not in zig-zag form). The 8 directions are, Horizontally Left, Horizontally Right, Vertically Up, Vertically Down and 4 Diagonal directions.
Note: The returning list should be lexicographically smallest. If the word can be found in multiple directions starting from the same coordinates, the list should contain the coordinates only once.
[Naive Search] Recursion - O(m × n × WordLength) Time and O(L) Space
We check every cell of the grid as a starting point and try to match the word in all 8 directions. If characters match continuously in any one direction, we confirm the word exists from that position.
Define 8 possible directions using two arrays
Traverse through all cells and for each cell (i, j) check if it matches first character, try all 8 directions from that cell using recursion.
At each step check bounds and character match
If found in any direction, return true from the recursive function and store (i, j) in the caller.
Output
{0,0} {0,2} {1,0}
[Expected Approach] Iterative - O(m × n × WordLength) Time and O(1) Space
Start from every cell of the grid and check whether the given word can be formed by moving in any one of the 8 directions. If characters keep matching in a straight direction, the word is found from that starting cell.
Define 8 possible directions using two arrays
Traverse the grid using nested loops. For each cell (i, j) check if it matches the first character of the word
If matches, try each direction, move step by step from the current cell
Compare remaining characters of the word one by one If out of bounds or mismatch occurs, stop that direction
If all characters match, store the cell (i, j) in result if word is found