Travel of Alphabets
InterviewTime limit2sMemory limit256 MB
Count all length-L walks on a letter grid and the distinct strings among them, discarding any word containing a, c, or m.
- Level
Easy3 of 10
- Topics
- Backtracking, DFS, Hash map
- Solved
- No attempts yet
Problem
Each cell of an grid holds one lowercase letter. Start on any cell and make moves, each one onto a cell that touches the current cell on the left, above, to the right, or below. The letters of the visited cells, read in visit order, spell a word of length .
Two rules govern a move. You cannot leave the grid. You may step onto a cell you have already visited, including the cell you just came from. When is 1 there is no move, so the letter in a single cell is already a word.
Build every word this way, over every starting cell and every sequence of moves. The letters a, c, and m are forbidden. Any word that contains at least one forbidden letter is thrown away. For example, ici, ahi, and mrk are all thrown away.
Count how many words survive, and how many distinct strings appear among them. A different starting cell or a different route counts as a separate word even when it spells the same string, but the distinct count charges that string only once.
Input
The first line contains the number of rows , the number of columns , and the word length , separated by spaces. (, , )
Each of the next lines holds one row of the grid: lowercase letters with no spaces.
Output
Print the number of words of length on the first line. Print how many of them are distinct on the second line.