Mowing the Field
InterviewTime limit2sMemory limit512 MB
Simulate the grid walk and report the smallest time gap between two visits to the same cell, or -1 when no cell repeats.
- Level
Easy3 of 10
- Topics
- Simulation, Hash map
- Solved
- No attempts yet
Problem
Farmer John is reliable at almost every part of running his farm, with one exception: he is terrible at mowing the grass promptly or in any sensible order.
The farm is a large 2D grid of square unit cells. At time John starts in one of these cells and mows the grass there, so at first that cell is the only one with cut grass. The rest of his route is given by statements. For example, if the first statement is "W 10", then for times through , that is the next 10 units of time, John steps one cell west at a time and mows the grass in every cell he passes. After finishing that statement he stands 10 cells west of where he started at time , and the grass in every cell along the way is cut.
John works so slowly that some of the grass he cuts grows back before he is done. Grass cut at time reappears at time .
John may pass through the same cell several times, but he says he never stepped on a cell whose grass was still cut. That is, every time he steps on a cell, his previous visit to that same cell was at least units of time earlier, so the grass had already grown back.
Find the largest value of for which John's claim holds.
Input
The first line contains (). Each of the next lines contains one statement in the form "D S". D is a character giving a direction, where N is north, E is east, S is south and W is west. S is the number of steps taken in that direction, with .
Output
Print on one line the largest value of for which John never steps on a cell with cut grass. If John never visits any cell more than once, print -1.
Hint
In the sample, John steps at time 17 on a cell he already stepped on at time 7, so can be at most 10. Otherwise the grass from the first visit has not grown back yet. He also steps at time 26 on a cell he visited at time 2, so is also at most 24. The first constraint is the tighter one, so the largest is 10.