Please Take My Gift

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.

Medium7GraphDFSGreedyImplementationNo attempts yetTime limit2sMemory limit512 MB

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 (i1,j)(i-1, j), S to (i+1,j)(i+1, j), W to (i,j1)(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. (1N,M10001 \le N, M \le 1\,000, 1<N×M10000001 < 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.