#K88147. Count Distinct Crops

    ID: 37244 Type: Default 1000ms 256MiB

Count Distinct Crops

Count Distinct Crops

In this problem, you are given a farm grid represented by a 2D matrix. Each cell in the matrix has a positive integer value representing fertile land or 0 representing barren land. A crop is defined as a connected region of fertile cells. Two cells are considered connected if they share an edge (i.e. adjacent in one of the four directions: up, down, left, or right).

Your task is to count the number of distinct crops in the given grid. Note that the actual values in fertile cells do not matter—only the connectivity is important.

In mathematical notation, if we define the grid as a matrix \(A\) with dimensions \(R \times C\), a crop is a connected component of cells \(A[i][j] \neq 0\) using the 4-adjacency relation. You are required to output the number of these connected components.

Note: If the grid is empty (i.e. no rows or columns), then the output should be 0.

inputFormat

The input is read from standard input (stdin) and is formatted as follows:

  1. The first line contains two integers \(R\) and \(C\) representing the number of rows and columns in the grid respectively.
  2. The next \(R\) lines each contain \(C\) space-separated integers. Each integer represents a cell in the grid. A value of 0 indicates a barren cell and any positive integer indicates a fertile cell.

If \(R = 0\) and \(C = 0\), it represents an empty grid.

outputFormat

Output a single integer to standard output (stdout) representing the number of distinct crops (i.e., connected components of fertile cells) in the grid.

## sample
3 3
1 1 0
0 1 0
1 0 1
3