The Worm Turns
InterviewTime limit1sMemory limit128 MB
Simulate a 20-cell worm on a 50x50 grid through a list of moves, stopping when it hits itself, leaves the board, or finishes.
- Level
Easy2 of 10
- Topics
- Simulation, Implementation, Queue, Array
- Solved
- No attempts yet
Problem
Worm is an old computer game. It comes in many versions, but they all involve steering a "worm" around the screen while trying not to run the worm into itself or into an obstacle.
Here we simulate a heavily simplified version. The game is played on a board whose cells are numbered so that the upper-left cell is . The first coordinate is the row and the second is the column , with and .
The worm is a chain of 20 connected cells. Two cells are connected when they are adjacent horizontally or vertically. At the start the worm is stretched out horizontally, occupying through , with its head at .
On each move the worm advances one cell East (E), West (W), North (N), or South (S). E and W change the column by and ; S and N change the row by and . The worm never moves back onto itself, so from the starting position a W move is impossible. Because of this, the only two cells that change on any move are the head and the tail: the head advances one cell and the tail is pulled forward by one cell. In particular, the head may move into the cell that the tail vacates on the very same move.
You are given a sequence of moves and must simulate them until one of the following happens:
- the worm runs into itself,
- the worm runs off the board, or
- the worm completes its entire list of moves.
In the first two cases, ignore the remaining moves in the list.
Input
The input contains several test cases. Each test case is given on two lines. The first line contains an integer (), the number of moves. A line containing marks the end of the input and must not be processed. The second line contains exactly characters, each one of E, W, N, or S with no separating spaces, giving the sequence of moves.
Output
For each test case, print exactly one line. Taking the first move as move 1 and letting be the move number you determine, the line must be exactly one of the following three:
The worm ran into itself on move m.The worm ran off the board on move m.The worm successfully made all m moves.