King's Walk
Time limit1sMemory limit256 MB
Move a king n cells over a letter grid to match the motto in as many positions as possible, breaking ties by the smallest coordinate sequence.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Matrix
- Solved
- No attempts yet
Problem
A chess king wants to take a walk across the Spring Field. The field is a rectangle, and every cell holds one lowercase Latin letter.
The king starts the walk on any cell of the field and makes moves. Each move follows the chess rule for a king: he steps to a cell that shares an edge or a corner with the current cell. Staying on the same cell does not count as a move. The king may visit the same cell several times during the walk.
The king therefore visits cells. Reading the letters of those cells in visiting order gives a string of length .
In the evening the king compares this string with the motto of his dynasty, which is also exactly letters long. If position of the motto and position of hold the same letter, the king promotes the -th pawn.
Find a route that promotes as many pawns as possible.
Input
The first line contains two integers and (), the size of the field.
Each of the next lines contains lowercase Latin letters, the description of the field.
The next line contains an integer ().
The last line contains the motto of the dynasty, a string of lowercase Latin letters.
Output
Print , the largest possible number of promoted pawns, on the first line.
On each of the next lines print the coordinates of one visited cell, in visiting order: the row number and the column number separated by a space. Rows are numbered from top to bottom starting at 1, and columns from left to right starting at 1.
If several routes promote pawns, print the lexicographically smallest one. Compare routes as the sequence of coordinates in visiting order, .