2008 Canadian Computing Competition, Day 2

Day 2, Problem 1: 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.

Sample Input

3 4
SWWW
SEWN
EEEN

Sample Output

2

Grading

You may assume that 40% of test cases will have 1 ≤ n, m ≤ 4. All test cases will have 1 ≤ n, m ≤ 1000. You solution must use at most 512MB of memory and run in at most 3 seconds.

All Submissions
Best Solutions


Point Value: 10
Time Limit: 3.00s
Memory Limit: 512M
Added: Dec 07, 2008

Languages Allowed:
C++03, PAS, C, HASK, ASM, RUBY, PYTH2, JAVA, PHP, SCM, CAML, PERL, C#, C++11, PYTH3

Comments (Search)

Don't you only need to put one at the W in the 2nd row 3rd column?

What if the cat starts somewhere along the boundary? In this case, the cat will never run into a trap, but instead circle indefinitely.