Do You Ever Feel Like A Plastic Bag?
You are a plastic bag located at on an infinite 2D grid.
For the next units of time, you know the weather forecast. At each time
(
), the wind blows in one of the following directions: north, east, south, west, or no wind.
Initially, you are stationary. At any time, you may choose to stop being stationary. Once you do, you will drift following the wind for all future times.
If you are at position at time
and the wind at time
is:
N, you will move toS, you will move toE, you will move toW, you will move toX, you will remain at
There are also Good Citizens. Each Good Citizen occupies a fixed grid cell. If you ever enter a cell occupied by a Good Citizen, they will put you in the bin, and you are immediately removed from the grid.
You are given a target cell . Determine the earliest time
at which you can stop being stationary such that:
- the bag reaches
at some time
, and
- the bag never enters a cell occupied by a Good Citizen before reaching
.
If no such starting time exists, output -1.
Input
The first line contains two space-separated integers and
, representing the number of turns of wind that will follow and the number of Good Citizens.
The next line also contains two space-separated integers and
, the coordinates of the target cell.
The following line contains a single string of characters, where each character is one of
N, S, E, W, X. The th character represents the weather at the
th time from
to
.
The following lines each contain integers
and
, the position of one of the
Good Citizens. Note that
may be zero.
Output
Output a single integer - the earliest time at which you can stop being stationary such that the bag reaches
at some time
, and the bag never enters a cell occupied by a Good Citizen before reaching
.
If no such starting time exists, output -1.
Notes
If the bag stops being stationary at time , it remains at
for the first
wind steps, and then begins moving according to the wind at time
.
The bag is removed if it occupies a cell containing a Good Citizen at any time from when it starts drifting until it reaches the target, including the starting cell and the target cell itself.
Example
Input 1
3 1
1 0
NES
1 1
Output 1
1
If you start at , you go to
then
and are removed by the Good Citizen there. If you wait until
, you move to
and reach the target safely.
Input 2
2 0
1 0
NN
Output 2
-1
No matter when you stop being stationary, the wind only moves north, so the -coordinate stays
. You can never reach the target
.
Input 3
7 1
2 0
NESWEEX
0 1
Output 3
4
Comments