#P1451. Counting Cells in a Rectangular Grid
Counting Cells in a Rectangular Grid
Counting Cells in a Rectangular Grid
A rectangular grid is composed of digits from 0 to 9. The digits from 1 to 9 represent parts of cells. A cell is defined as a connected component of any digits between 1 and 9 where connectivity is established using the four cardinal directions (up, down, left, right). Given such a grid, your task is to count the number of distinct cells.
Note that two adjacent numbers (horizontally or vertically) that are nonzero (i.e. between 1 and 9) are considered part of the same cell regardless of whether their values are identical.
Mathematical definition:
Let \( G[i][j] \) denote the digit at row \( i \) and column \( j \). A cell is a maximal set \( S \) of positions such that for any \( (i,j)\in S \), \( G[i][j] \in \{1,2,3,4,5,6,7,8,9\} \) and for any two positions \( (i_1,j_1), (i_2,j_2) \) in \( S \), there exists a sequence of positions \( (i_1,j_1), (i_2,j_2), \dots, (i_k,j_k) \) in \( S \) where consecutive positions are adjacent (up, down, left, right).
inputFormat
The first line contains two integers \( R \) and \( C \), representing the number of rows and columns of the grid respectively.
Each of the following \( R \) lines contains a string of \( C \) digits (each between 0 and 9) without spaces.
outputFormat
Output a single integer, the number of distinct cells in the grid.
sample
3 3
010
111
010
1