This page is still under construction.

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

Please Take My Gift

Time limit2sMemory limit512 MB

Summary
Each cell of a grid holds a direction; every walk follows those arrows forever. Find the fewest cells to mark so every walk visits a marked cell.
Level

Medium7 of 10

Topics
Graph, DFS, Greedy, Implementation
Solved
No attempts yet

Problem

Wookje is a devoted fan of Gusagwa. Today Wookje wants to deliver a gift to Gusagwa. After several days of observation, Wookje has worked out Gusagwa's movement pattern completely.

The area where Gusagwa lives is a rectangular map of size N×MN \times M, divided into square cells of size 1×11 \times 1. Gusagwa's position is written as (i,j)(i, j), which means the cell in the ii-th row from the top and the jj-th column from the left.

Each cell of the map holds one of the letters N, W, E, S, and Gusagwa moves according to that letter. When Gusagwa stands on cell (i,j)(i, j), the letter N teleports Gusagwa to (i−1,j)(i-1, j), S to (i+1,j)(i+1, j), W to (i,j−1)(i, j-1), and E to (i,j+1)(i, j+1). Gusagwa never gets tired and keeps moving forever.

Wookje does not know where Gusagwa is right now, so Wookje wants a way to deliver the gift no matter which cell Gusagwa starts from. When Gusagwa arrives at a cell that holds a gift, Gusagwa always takes it. Write a program that finds the minimum number of cells on which gifts must be placed so that Gusagwa always takes a gift, regardless of the starting cell.

Input

The first line contains the height NN and the width MM of the map. (1≤N,M≤1 0001 \le N, M \le 1\,000, 1<N×M≤1 000 0001 < N \times M \le 1\,000\,000)

Each of the next NN lines contains one row of the map. Each line is a string of length MM made only of the letters N, W, E, S.

Following the letters on the map never leads outside the map.

Output

Print on the first line the minimum number of cells on which gifts must be placed.

Examples3

  1. Example 1

    Input
    3 4
    SWWW
    SEWN
    EEEN
    
    Expected output
    2
    
  2. Example 2

    Input
    3 3
    SSW
    SNW
    EEN
    
    Expected output
    1
    
  3. Example 3

    Input
    2 2
    EW
    EW
    
    Expected output
    2