This page is still under construction.

Parts of this page are still being built. What you see may change.

The Worm Turns

Interview

Time limit1sMemory limit128 MB

Summary
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 50×5050 \times 50 board whose cells are numbered so that the upper-left cell is (1,1)(1, 1). The first coordinate is the row rr and the second is the column cc, with 1≤r≤501 \le r \le 50 and 1≤c≤501 \le c \le 50.

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 (25,11)(25, 11) through (25,30)(25, 30), with its head at (25,30)(25, 30).

On each move the worm advances one cell East (E), West (W), North (N), or South (S). E and W change the column by +1+1 and −1-1; S and N change the row by +1+1 and −1-1. 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 nn (n<100n < 100), the number of moves. A line containing n=0n = 0 marks the end of the input and must not be processed. The second line contains exactly nn 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 mm 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.

Examples1

  1. Example 1

    Input
    18
    NWWWWWWWWWWSESSSWS
    20
    SSSWWNENNNNNWWWWSSSS
    30
    EEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
    13
    SWWWWWWWWWNEE
    0
    
    Expected output
    The worm successfully made all 18 moves.
    The worm ran into itself on move 9.
    The worm ran off the board on move 21.
    The worm successfully made all 13 moves.