Buggy Rover

시간 제한2초메모리 제한2048 MB

요약
격자와 로버의 이동 순서가 주어질 때, 이동이 유효하도록 방향 순서가 바뀌었을 최소 횟수를 구한다.
난이도

보통10점 중 6점

유형
동적 계획법, 시뮬레이션, 그리디
정답자
아직 제출이 없습니다

문제

The International Center for Planetary Cartography (ICPC) uses rovers to explore the surfaces of other planets. As we all know, other planets are flat surfaces which can be perfectly and evenly discretized into a rectangular grid structure. Each cell in this grid is either flat and can be explored by the rover, or rocky and cannot.

Today marks the launch of their brand-new Hornet rover. The rover is set to explore the planet using a simple algorithm. Internally, the rover maintains a direction ordering, a permutation of the directions north, east, south, and west. When the rover makes a move, it goes through its direction ordering, chooses the first direction that does not move it off the face of the planet or onto an impassable rock, and makes one step in that direction.

Between two consecutive moves, the rover may be hit by a cosmic ray, replacing its direction ordering with a different one. ICPC scientists have a log of the rover’s moves, but it is difficult to determine by hand if and when the rover’s direction ordering changed. Given the moves that the rover has made, what is the smallest number of times that it could have been hit by cosmic rays?

입력

The first line of input contains two integers rr and cc, where rr (1≤r≤2001 ≤ r ≤ 200) is the number of rows on the planet, and cc (1≤c≤2001 ≤ c ≤ 200) is the number of columns. The rows run north to south, while the columns run west to east.

The next rr lines each contain cc characters, representing the layout of the planet. Each character is either ‘#’, a rocky space; ‘.’, a flat space; or ‘S’, a flat space that marks the starting position of the rover. There is exactly one ‘S’ in the grid.

The following line contains a string ss, where each character of s is ‘N’, ‘E’, ‘S’, or ‘W’, representing the sequence of the moves performed by the rover. The string ss contains between 11 and 10,00010\\, 000 characters, inclusive. All of the moves lead to flat spaces.

출력

Output the minimum number of times the rover’s direction ordering could have changed to be consistent with the moves it made.

예제3

  1. 예제 1

    입력
    5 3
    #..
    ...
    ...
    ...
    .S.
    NNEN
    
    예상 출력
    1
    
  2. 예제 2

    입력
    3 5
    .###.
    ....#
    .S...
    NEESNS
    
    예상 출력
    0
    
  3. 예제 3

    입력
    3 3
    ...
    ...
    S#.
    NEESNNWWSENESS
    
    예상 출력
    4