Can a Word Follow a Grid Chain?
Problem statement
Return whether word can be formed by a continuous chain of characters in grid.
For this exercise, assume the grid is represented by equal-length lowercase row strings. A word may start at any cell. Each next character must be in the immediately adjacent cell up, down, left or right; diagonal moves are excluded.
For this exercise, assume a cell may be used at most once in one word path. Do not modify the grid or requested word. A word need not be present, and a word longer than the board cell count is valid but cannot be formed.
Return true when at least one complete allowed path spells the word, and false otherwise.
Function
existsGridWord(grid: String[], word: String) → booleanExamples
Example 1
grid = ["abc","hgd","ife"]word = "abcdefghi"return = trueAuthored example: the nine-cell path moves right, down, left and up while visiting every cell once.
Example 2
grid = ["ab","cd"]word = "aba"return = falseAuthored example: spelling aba would require returning to the same a cell, which is disallowed.
Example 3
grid = ["ab","cd"]word = "dcab"return = trueAuthored example: d to c to a to b uses left, up and right, so restricting movement to right/down would miss it.
Constraints
- For this exercise, assume
1 <= grid.length <= 3and1 <= grid[0].length <= 3. All rows have the same length; the board has at most9cells. - For this exercise, assume every requested word has length from
1through9. - For this exercise, assume all characters are lowercase English letters. Words longer than the board cell count are valid and cannot be formed.