#C5947. Counting Islands
Counting Islands
Counting Islands
Given a grid with n rows and m columns, where each cell is either a '.'
or a '*'
, your task is to count the number of islands. An island is defined as a maximal group of adjacent '.'
cells connected horizontally or vertically. Use an efficient algorithm such as DFS or BFS to traverse the grid.
For example, consider the grid below:
.*... .*.*. ..*.. *.**. .*..*
The number of islands in this grid is 4.
Note: There is no mathematical formula needed for this problem.
inputFormat
The input is read from stdin
and is structured as follows:
- The first line contains two integers:
n
andm
, which represent the number of rows and columns of the grid respectively. - The following
n
lines each contain a string of lengthm
composed solely of the characters'.'
and'*'
.
outputFormat
Print to stdout
a single integer that denotes the number of islands found in the grid.
5 5
.*...
.*.*.
..*..
*.**.
.*..*
4