#K40262. Count Accessible Regions

    ID: 26604 Type: Default 1000ms 256MiB

Count Accessible Regions

Count Accessible Regions

In this problem, you are given several grids where each cell is either accessible (represented by a '1') or blocked (represented by a '0'). Your task is to determine the number of connected regions of accessible cells in each grid. Two cells are connected if they share an edge, i.e. they are adjacent vertically or horizontally. In mathematical terms, cells \((i, j)\) and \((k, l)\) are connected if \(|i-k|+|j-l|=1\).

Each test case provides the dimensions of the grid and the grid itself. For each grid, compute the number of connected components (regions) consisting only of cells with '1'. If there are no accessible cells, the result is 0.

inputFormat

The input is read from stdin and is formatted as follows:

T
n1 m1
row1
row2
...
rown1
n2 m2
row1
row2
...
rown2
...

where T is the number of test cases. For each test case, the first line contains two integers n and m representing the number of rows and columns of the grid. Each of the following n lines contains a binary string of length m. A '1' indicates an accessible cell, and a '0' indicates an obstacle.

outputFormat

For each test case, print a single integer on a new line representing the number of connected accessible regions found in the grid. The output is written to stdout.

## sample
4
4 5
11000
11000
00101
00001
3 3
101
010
101
3 3
000
000
000
2 2
10
01
3

5 0 2

</p>