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.


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 the minimum number of traps needed.


3 4


hide comments
jatin03: 2017-07-11 18:24:15

Did it in second attempt dfs :)

naks: 2017-07-11 17:56:36

use disjoint sets!!! no bfs....

shahzada: 2017-06-25 08:16:51


adityaghosh96: 2017-06-18 23:00:20

Disjoint Sets. If you use 2d pair 2d array for roots, write the FindRoot function carefully.

ayushagg31: 2017-06-14 03:12:31

weakly connected component....finally ac!!

code_aim: 2017-05-25 18:01:56

Easy bfs.

candide: 2017-05-03 18:01:40

AC in Python (PyPy) but TLE in CPython. Nice question. Perhaps the example could receive an explanation. Chirag Gupta testcases are helful. As explained by sarthakshah30, you only have to find the number of connected components. Avoid deep recursion in Python. No problem with EOL input format.

Last edit: 2017-05-03 18:09:47
cake_is_a_lie: 2017-03-03 21:57:52

So the difference between 0.02 and 0.00 was the C++ compiler used (namely C++ as opposed to C or C++14) ... or maybe just luck?

sarthakshah30: 2017-03-03 14:42:47

weakly connected component in directed graph. simple

shubham2305: 2017-02-08 13:47:20

ac in 2nd go!
array size error in 1st go.
i think i am getting use to silly WA's :-(

Added by:JaceTheMindSculptor
Time limit:0.195s-0.902s
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