#K61392. Counting Distinct Groups of Trees in a Garden

    ID: 31299 Type: Default 1000ms 256MiB

Counting Distinct Groups of Trees in a Garden

Counting Distinct Groups of Trees in a Garden

John owns a rectangular garden represented as an \(M \times N\) grid. Each cell of the grid is either empty (denoted by 0) or has a tree (denoted by 1). Two trees are part of the same group if they are horizontally or vertically adjacent (diagonal adjacency is not considered).

Your task is to count the number of distinct groups of connected trees in the garden.

Example:

Input:
4 5
1 0 0 1 0
1 0 0 1 0
0 1 1 0 0
0 0 0 0 1

Output: 4

</p>

inputFormat

The input is read from standard input (stdin) and has the following format:

  • The first line contains two integers, \(M\) and \(N\), representing the number of rows and columns, respectively.
  • The next \(M\) lines each contain \(N\) space-separated integers (either 0 or 1) representing the grid.

outputFormat

Output a single integer to standard output (stdout) - the number of distinct groups of connected trees.

## sample
4 5
1 0 0 1 0
1 0 0 1 0
0 1 1 0 0
0 0 0 0 1
4

</p>