All Independently Formable Grid Words
Problem statement
Return every requested word that 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 list. A word need not be present, and a word longer than the board cell count is valid but cannot be formed.
For this exercise, assume each input entry is checked independently. Return qualifying entries in input order, including duplicates. A successful entry does not consume cells for another entry. Return an empty array for an empty list or when no entry is formable.
Function
formableGridWords(grid: String[], words: String[]) → String[]Examples
Example 1
grid = ["ab","cd"]words = ["dcab","aba","ab","dcab"]return = ["dcab","ab","dcab"]Authored example: dcab and ab are independently formable; aba requires cell reuse. The repeated dcab entry is retained in its original position.
Example 2
grid = ["abc","hgd","ife"]words = ["abcdefghi","ihgfedcba","a","xy","abcdefghi","abcfi"]return = ["abcdefghi","ihgfedcba","a","abcdefghi"]Authored example: full-board forward and reverse paths may reuse the board across different entries. Missing or nonadjacent spellings are excluded, and repeated successful entries remain.
Example 3
grid = ["a"]words = []return = []Authored example: an empty requested list produces an empty result.
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.
- For this exercise, assume
0 <= words.length <= 6.