#K91132. Count Isolated Land Groups
Count Isolated Land Groups
Count Isolated Land Groups
You are given a grid with M rows and N columns. Each cell of the grid is either land or water, represented by the characters 'L' and 'W' respectively. Two land cells are considered part of the same group if they are adjacent horizontally or vertically. Your task is to count the number of isolated groups of land.
Connectivity: Two cells are connected if and only if they share a side (up, down, left, or right). Diagonal cells are not connected.
Input Format: The first line contains two integers M and N. The following M lines each contain a string of length N consisting only of 'L' and 'W'.
Output Format: Output a single integer: the number of isolated groups of land.
Mathematical Formulation:
Let \(G\) be the grid and \(G[i][j]\) be either 'L' or 'W'. Define a function \(f(i, j)\) that marks all cells in the group containing \(G[i][j]\) when \(G[i][j] = 'L'\). Then the answer is the number of times \(f(i, j)\) is applied over the grid such that all connected land cells are visited. This can be formulated as:
[ \text{Answer} = \sum_{i=0}^{M-1} \sum_{j=0}^{N-1} \mathbb{1}_{{G[i][j] = 'L'}} \text{, with DFS/BFS propagation to mark connected cells.} ]
inputFormat
The input is given from standard input and has the following format:
- The first line contains two space-separated integers: M (the number of rows) and N (the number of columns).
- The following M lines each contain a string of length N consisting of the characters 'L' and 'W'.
outputFormat
Output a single integer to standard output representing the number of isolated groups of land in the grid.
## sample5 5
LWLWL
LLLLL
LWLWL
LLLLL
LWLWL
1