Tähekabe
InterviewTime limit1sMemory limit1024 MB
On an N x N letter grid, decide for each of up to 10 query words whether a simple path from the start cell spells it, without reusing a cell.
- Level
Medium5 of 10
- Topics
- Backtracking, DFS, Matrix, Brute force
- Solved
- No attempts yet
Problem
Tähekabe is a board game played on an grid where every cell holds a single letter. In this task we consider a simplified version with just one player and one piece (normally 2–4 players play, each with 4 pieces).
The player moves the piece one cell at a time — up, down, left, or right (never diagonally) — so that the letters the piece steps onto spell out a word. The letter on the starting cell is not counted as part of the word. For example, starting from one cell and stepping onto neighbouring cells in turn can spell the word "TEST".

There is a restriction that no cell may be used more than once while forming a single word. For example, on the grid shown above the word "KIRI" cannot be formed: after forming "KIR" the "I" cell has already been used, so the piece may not return to it.
Write a program that, given the state of the board, determines which of the given words the player is able to form.
Input
The first line contains the board size () and the row number and column number of the starting cell (rows are numbered from top to bottom and columns from left to right, through ). Each of the next lines contains exactly letters describing the state of the board. The next line contains the number of words (), followed by lines, each containing one word of length to . Both the board and the words use only uppercase Latin letters.
Output
Print those input words that the player is able to form in the given board state. Print each such word on its own line, in the same order as they appear in the input. If the player cannot form any word, print the text EI SAA on a single line.