Counting Lakes

medium dfs bfs graphs arrays 2000 ms · 128 MB

Counting Lakes

You are given a satellite scan of a rectangular area with R rows and C columns. Each cell is either land (.) or water (#). Two water cells belong to the same lake if they are adjacent, where adjacency includes diagonals: any cell sharing a side or a corner with another water cell is connected to it (8-directional adjacency). A lake is a maximal group of water cells connected this way.

Count the number of lakes, and report how many cells each lake contains, largest lake first.

Input

The first line contains two integers R and C (1 ≤ R, C ≤ 2000) — the number of rows and columns.

Each of the next R lines contains a string of exactly C characters, each either . (land) or # (water).

Output

Print a single integer k — the number of lakes.

If k > 0, print a second line with the k lake sizes, in descending order, separated by single spaces. If k = 0 (no water at all), omit the second line.

Notes

In the first example, water cells (0,2) and (1,1) (0-indexed) touch only at a corner, so together they form one lake of size 2. Further down, (3,2), (3,4), and (4,3) all chain together through corner touches into a single lake of size 3. There are no other water cells, so the answer is 2 lakes, with sizes 3 and 2.

In the second example, every water cell touches the centre cell (1,1) diagonally, so all 5 water cells form one lake.

Example 1

Input

5 5
..#..
.#...
.....
..#.#
...#.

Output

2
3 2

Example 2

Input

3 3
#.#
.#.
#.#

Output

1
5

Hints · reveal one at a time if you're stuck

Hint 1

Think of the water cells as nodes of a graph, where two cells are linked if they touch, including diagonally. A lake is then a connected component, so you need to find each component and count its cells.

Hint 2

The grid can be 2000 by 2000 with one lake covering everything, so a recursive flood fill could run far too deep. Do the search with an explicit stack or queue, and mark a cell as seen when you push it so it is never added twice.

report an issue Prefer your own editor? sooks prep 85 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.