Crate label search
EasyOnline Assessment
Find where a word is written in a grid of crate labels.
A warehouse wall holds crates in a rectangular grid; each crate carries one lowercase letter. grid is a list of equal-length strings, one per row, row 0 at the top. A word is present if it can be read in a straight line of consecutive crates in one of four directions (diagonals do not count):
"R": to the right (increasing column)"D": downward (increasing row)"L": to the left (decreasing column)"U": upward (decreasing row)
The start of a reading is the crate holding the word's first letter, wherever the line ends up (so a word read leftwards starts at its right-hand end). A word of one letter is present at every crate with that letter.
Among all the places the word is present, report the one whose start comes first in reading order: smallest row, then smallest column. If several directions work from that same start, prefer them in the order R, D, L, U.
Input: grid, a list of strings, and word, a string.
Output: a list [row, column, direction] with 0-based row and column and the direction letter as a string, or [] if the word is nowhere in the grid.
Example 1
- Input:
- [["rab","xyz","qwe"],"bar"]
- Output:
- [0,2,"L"]
- Explanation
- The word
baris spelled leftwards along row 0: thebis in column 2, thena, thenr. The answer is the position of the first letter,[0, 2, "L"].
Example 2
- Input:
- [["xax","xbx","xcx","abc"],"abc"]
- Output:
- [0,1,"D"]
- Explanation
abcappears twice: going down column 1 from row 0 and going right along row 3. Row 0 comes before row 3 in reading order, so the downward match wins:[0, 1, "D"], even though the rightward word is the one you would find first by sweeping directions one at a time.
Example 3
- Input:
- [["ax","xb"],"ab"]
- Output:
- []
- Explanation
- The letters
aandbtouch only diagonally, and diagonals do not count, so the answer is[].
Constraints
1 <= grid.length <= 20, all rows have the same length1 <= grid[i].length <= 201 <= word.length <= 20gridandwordcontain only lowercase letters