#K96262. Connected Components in a Grid

    ID: 39048 Type: Default 1000ms 256MiB

Connected Components in a Grid

Connected Components in a Grid

You are given a grid of size \( n \times m \) consisting of characters '.' and '#'. A connected component is defined as a maximal set of cells containing the character '.' such that every two cells in this set are connected vertically or horizontally (diagonal connections are not considered).

Your task is to compute the number of connected components in the grid. More formally, consider the grid cells as nodes of a graph where there is an edge between two nodes if and only if they are adjacent vertically or horizontally and both contain '.'. You need to count the number of connected components in this graph.

The input begins with two integers \( n \) and \( m \) \( (1 \leq n, m \leq 1000) \) representing the number of rows and columns respectively. This is followed by \( n \) lines each containing a string of length \( m \) made up of the characters '.' and '#'.

Print a single integer representing the number of connected components of '.' characters.

inputFormat

The first line contains two space-separated integers \( n \) and \( m \). Each of the next \( n \) lines contains a string of length \( m \) consisting only of the characters '.' and '#'.

Example:

3 3
..#
#.#
##.

outputFormat

Output a single integer -- the number of connected components of '.' in the grid.

Example:

2
## sample
3 3
..#
#.#
##.
2