Under construction

Still being built. Things may change

Why the Williamson's Sapsucker Came Up to Information Island

Interview

Time limit1sMemory limit256 MB

Summary
On a grid with walls, find which of three food cells is nearest to the start cell 2, and print TAK with that distance, or NIE if none is reachable.
Level

Medium4 of 10

Topics
BFS, Graph, Matrix, Shortest path
Solved
No attempts yet

Problem

A family of three Williamson's sapsuckers has come up to Information Island.

The three Williamson's sapsuckers were sitting together somewhere on the second floor of Information Island, resting, when they spotted cheonggukjang, sushi, and mac and cheese far away. The father wants cheonggukjang, the mother wants sushi, and the child wants mac and cheese. So the three decided to go eat the food closest to their current position.

The second floor of Information Island is represented as an n×mn \times m grid. If some Ai,jA_{i,j} is 0, it is an empty corridor that can be passed through; if it is 1, it is blocked by an obstacle and cannot be passed through. The Williamson's sapsucker family is 2, cheonggukjang is 3, sushi is 4, and mac and cheese is 5. A Williamson's sapsucker can move one cell up, down, left, or right per unit time. Since 2, 3, 4, and 5 are not obstacles, they can be passed through. You cannot leave the grid, and the distance from the starting point to the starting point is 0. The starting point is the position of the Williamson's sapsucker, that is, the position of 2.

Which food can the Williamson's sapsucker family reach faster?

Input

The first line gives the size of the second floor of Information Island, nn and mm. (1≤n,m≤30001 \le n, m \le 3000, 4≤n×m≤9×1064 \le n \times m \le 9 \times 10^6)

The following nn lines of mm columns give Ai,jA_{i,j}, consisting only of 0, 1, 2, 3, 4, and 5. No space is given between Ai,jA_{i,j} and Ai,j+1A_{i,j+1}.

Each of 2, 3, 4, and 5 appears exactly once, and everything other than 2, 3, 4, and 5 is 0 or 1.

Output

On the first line, print "TAK" (meaning YES in Polish), and on the second line, print the shortest distance from the current position to the food that can be reached fastest.

If no food can be eaten, print "NIE" (meaning NO in Polish). Do not print anything else.

When printing TAK and NIE, do not print the quotation marks, and they must be printed in uppercase.

Examples4

  1. Example 1

    Input
    3 3
    200
    003
    045
    Expected output
    TAK
    3
    
  2. Example 2

    Input
    3 3
    210
    113
    045
    Expected output
    NIE
    
  3. Example 3

    Input
    3 3
    200
    110
    435
    Expected output
    TAK
    4
    
  4. Example 4

    Input
    5 5
    11111
    40002
    10101
    30001
    11511
    Expected output
    TAK
    4