#K37282. Connected Buildings Groups
Connected Buildings Groups
Connected Buildings Groups
Given an (m \times n) grid representing a map of buildings, where each cell is either 1 (indicating a building) or 0 (empty), your task is to count the number of distinct connected groups of buildings. Two cells are considered connected if they share a side (up, down, left, or right).
This can be formulated as finding the number of connected components in the grid using depth-first search (DFS). In mathematical terms, if we define a connected component detection function (\delta(\text{cell})), the final answer is given by: $$\text{Count} = \sum_{i=1}^{m} \sum_{j=1}^{n} \delta(matrix[i][j])$$ where (\delta(matrix[i][j]) = 1) when a new connected component is discovered.
inputFormat
The first line contains two integers (m) and (n) (the number of rows and columns, respectively). Each of the next (m) lines contains (n) space-separated integers (either 0 or 1) representing the grid.
outputFormat
Print a single integer representing the number of connected groups of buildings in the grid.## sample
4 5
1 1 0 0 0
0 1 0 1 1
1 0 0 0 0
0 0 1 1 1
4