Lemmings, Lemmings Everywhere. But Not For Long.
Time limit1sMemory limit128 MB
Given a grid where every cell holds a lemming with a cyclic four-direction agenda, simulate their simultaneous movement and report how many steps until all lemmings exit the board.
- Level
Medium5 of 10
- Topics
- Simulation, Implementation, Matrix
- Solved
- No attempts yet
Problem
On an board there is a lemming on every square. Every second the lemmings all try to move one square north, south, east, or west, following the rules below. Each lemming has an agenda, a permutation of the four directions (for example NWES).
- Each lemming's current direction starts as the first direction in its agenda.
- At each time step, each lemming tries to move one square in its direction . For a lemming :
- If would take off the board, leaves the board (the world has one fewer lemming). Otherwise 's target is another square.
- If 's target square is empty, or is about to become empty because the lemming on it is leaving, and no other lemming is also trying to move onto that square, then moves onto it. In this case keeps the same direction for the next step.
- Otherwise (another lemming is also trying to move onto 's target square, or that square holds a lemming that cannot move), stays put and advances to the next direction in its agenda, wrapping around if necessary.
Two lemmings that want to exchange squares may do so, unless some other lemming is also trying to move onto one of their two squares (in which case all three stay put). The lemmings keep moving until every one of them has left the board. Determine how many steps this takes.
Input
The input consists of several test cases. Each test case begins with a line containing two positive integers and , the number of rows and columns; each is at most . The board is oriented so that square is the southwest corner and square is the southeast corner. Then come the agendas of the lemmings, each a permutation of the string NESW, separated by single spaces, with agendas per line (except possibly the last). The agendas are assigned to lemmings row by row: the first to the lemming on , the second to , and so on. The line 0 0 follows the last test case and terminates the input.
Output
For each test case, output one line containing the case number followed by the number of steps until the last lemming or lemmings fall off the board, in the format
Case k: steps
Use only single spaces to separate the items on the line.