Sleepwalker
Time limit1sMemory limit128 MB
A self-similar walk on a 3^k by 3^k grid is defined by a recursive rewrite; given a starting tile on the walk and a hole tile, find the number of steps until the walk reaches the hole.
- Level
Hard9 of 10
- Topics
- Recursion, Divide and conquer, Simulation, Math
- Solved
- No attempts yet
Problem
A building has a flat, square roof of size , with its sides parallel to the north-south and east-west directions. The roof is covered with unit square tiles (each of side length ), but one tile has been removed, leaving a hole large enough to fall through.
The tiles form a rectangular grid, so each tile has integer coordinates. The tile in the southwestern corner has coordinates . The first coordinate increases toward the east, and the second increases toward the north.
A sleepwalker wanders across the roof. In each step he moves from the tile he stands on to an adjacent tile: east (E), west (W), south (S), or north (N). His walk always starts from the southwestern corner tile. The walk is described by a word over the letters N, S, E, W, where each letter denotes one step in that direction.
For the walk is:
d_1 = EENNWSWN
For the walk is:
d_2 = NNEESWSEENNEESWSEEEENNWSWNNEENNWSWNNEENNWSWNWWWSSENESSSSWWNENWWSSWWNENWNEENNWSWN
In general, for , the walk on a roof of size is built from the walk as follows:
d_{k+1} = a(d_k) E a(d_k) E d_k N d_k N d_k W c(d_k) S b(d_k) W b(d_k) N d_k
Here , , and are permutations of the four direction letters:
Applying a function to a word rewrites every letter according to its column in the table above. For example, , , and .
We begin watching the sleepwalker at the moment he stands on the tile . After how many steps will he fall into the hole left by the removed tile at ?
The pictures below show the sleepwalker's path on roofs of size and . In the case, the tile where the observation begins and the hole are both marked.


Write a program that reads the roof size , the tile where the sleepwalker stands when the observation begins, and the tile that was removed to make the hole, then computes and prints how many steps the sleepwalker takes before falling into the hole.
Input
The first line contains one integer with , giving the roof size . Each of the next two lines contains two integers and separated by a space, with and . The two numbers on the second line are the coordinates of the tile on which the sleepwalker stands when the observation begins. The two numbers on the third line are the coordinates of the hole. The input is guaranteed to be such that the sleepwalker eventually falls into the hole.
Output
Print a single line containing the number of steps on the sleepwalker's path from the starting tile to the hole.