#158 · Recursion and backtracking · Advanced · 140 XP · about 25 min
A grid of letters is given as a list of equal-length strings, one per row. A word can be traced in the grid if you can start on a cell holding its first letter and reach each next letter by stepping to a neighbouring cell (up, down, left or right, not diagonally), never using the same cell twice in one word.
Write word_in_grid(grid, word) that returns True if word can be traced, and False otherwise.
grid = ["SNAKE", "PYTHO", "CODEN"] word_in_grid(grid, "PYTHON") # returns True word_in_grid(grid, "CODE") # returns True word_in_grid(grid, "NODE") # returns False
"PYTHON" runs along the middle row and turns down for the N. "NODE" fails: the N in the bottom-right corner touches an O, but no D touches that O, and the other N has no O beside it.
1 <= len(word) <= 15Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.