HERDING - Herding


Oh no! A number of stray cats have been let loose in the city, and as the City Cat Catcher, you have been assigned the vital task of retrieving all of the cats. This is an ideal opportunity to test your latest invention, a cat trap which is guaranteed to retrieve every cat which walks into a square-shaped subsection of the city.

Fortunately, you have the assistance of one of the world's foremost cat psychologists, who has the amazing ability of predicting, given a square subsection of the city, exactly which of the four cardinal directions (north, east, south or west) the cat will head. While this information is handy, you still don't know where all the cats currently are.

In order to prove the cost-effectiveness of your method to the City it would, of course, be important to minimize the number of traps used.

Input

The input will begin with a line consisting of two numbers n and m, separated by a space (1 ≤ n, m ≤ 1000). The city will be an n x m grid of square subsections. The next n lines will each consist of a string of length m, consisting of the letters 'N', 'E', 'S', or 'W', representing north, east, south and west, respectively. (The first character of the first line will be the northwesternmost point.) The direction in the square is the direction which cats will head if they are in that square. The cat psychologist assures you that cats have no interest in leaving the city.

Output

Output the minimum number of traps needed.

Example

Input:
3 4
SWWW
SEWN
EEEN

Output:
2

hide comments
Waseem Ahmed: 2021-06-15 17:52:00

Solved it in second attempt finally using simple loops (a DFS variant)!!!

Thanks @donnie_darko (Chirag Gupta)!! May not have solved it without your test cases. Thanks!

yuvrajsharma: 2020-10-03 18:37:16

AC in first go
modified dfs

vishalshrm539: 2020-08-22 20:19:06

BFS!

vickyvanshaj: 2020-06-09 21:05:44

AC in one go!!

shubham_it_bit: 2020-05-05 17:44:55

good one .. a bit different and interesting problem if done with dfs

smug__face: 2020-03-24 19:15:10

4 4
SWWW
SEEW
SSWS
NNWN

Can someone explain this case?

dkkv0000: 2020-01-19 14:01:47

good problem on dfs 3rd attempt AC

sohit5012: 2019-07-14 10:07:57

Use DFS , for some reason Bfs gives TLE, maybe its the overhead of using a queue.

haiderbaig: 2019-03-14 14:13:34

Solved by creating a 2D array and traversing it according to the direction mentioned on the cells. Also have to keep track of visited cells.
I don't know how this is a DFS problem !

ab_biswas09: 2019-01-16 20:29:47

Solved using DFS by keeping track of visited nodes in the current recursion stack


Added by:JaceTheMindSculptor
Date:2009-04-07
Time limit:0.902s-1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: C99 ERL JS-RHINO
Resource:Canadian Computing Competition 2008 Stage 2 Day 2 Problem D