#K93267. Connected Components in a Grid
Connected Components in a Grid
Connected Components in a Grid
This problem asks you to count the number of connected components of blocks in a 2D grid. The grid is composed of rows and columns where each cell is either a block represented by '#' or an empty cell represented by '.'. Two blocks are considered connected if they are adjacent vertically or horizontally (not diagonally).
Mathematically, the number of connected components can be described as the sum over all cells, where a new component is counted when a block that is not connected to any previously counted block is encountered. For example, using the formula: $$components = \sum_{i=1}^{N} \sum_{j=1}^{M} f(i,j)$$, where $$f(i,j)=1$$ if the cell at ((i,j)) is a new component, and 0 otherwise.
Your task is to implement an algorithm (using DFS, BFS, or any graph traversal technique) to compute the number of these connected components.
inputFormat
The first line of input contains two integers (N) and (M) (the number of rows and columns in the grid, respectively). This is followed by (N) lines, each containing a string of (M) characters, where each character is either '#' (denoting a block) or '.' (denoting an empty cell).
outputFormat
Output a single integer representing the number of connected components of '#' blocks in the given grid.## sample
4 5
#.#.#
..##.
##..#
.#..#
5