This problem was asked by Microsoft.

Given a 2D matrix of characters and a target word, write a function that returns whether the word can be found in the matrix by going left-to-right, or up-to-down.

For example, given the following matrix:

[['F', 'A', 'C', 'I'],
 ['O', 'B', 'Q', 'P'],
 ['A', 'N', 'O', 'B'],
 ['M', 'A', 'S', 'S']]

and the target word 'FOAM', you should return true, since it's the leftmost column. Similarly, given the target word 'MASS', you should return true, since it's the last row.

Idea behind the solution

The secret here is just to track how many elements has been printed, as well as keep tracking the current element printed, checking whether it is possible to print the next element or if it is needed to change the "print direction".

Also, to remember which element has been printed, null is set on the element that has just been printed.

Please check the main.js snippet for the solution.

This solution originally posted at: Github by @Murillo2380