#P9243. [蓝桥杯 2023 省 B] 岛屿个数
[蓝桥杯 2023 省 B] 岛屿个数
Problem Description
Xiao Lan obtained a grid map of size . It can be viewed as a 2D array containing only the characters 0 (sea) and 1 (land). Outside the map, everything can be considered sea. Each island is formed by connecting adjacent 1 cells in the four directions up, down, left, and right.
On the cells occupied by island , if we can choose distinct cells such that their coordinates can form an ordering $\left(x_{0},y_{0}\right),\left(x_{1},y_{1}\right),\ldots,\left(x_{k-1},y_{k-1}\right)$, where is obtained from by moving exactly once up/down/left/right (), then these cells form a “cycle”.
If all cells occupied by another island are located strictly inside this “cycle”, then we consider island to be a sub-island of island . If is a sub-island of , and is a sub-island of , then is also a sub-island of .
How many islands are there on this map? When counting, you do not need to count the number of sub-islands.
Input Format
The first line contains an integer , meaning there are sets of testdata.
Then follow test cases. For each test case, the first line contains two integers separated by spaces, indicating the map size. Then lines follow, each containing characters, and each character is only 0 or 1.
Output Format
For each test case, output one line containing one integer, which is the answer.
2
5 5
01111
11001
10101
10001
11111
5 6
111111
100001
010101
100001
111111
1
3
Hint
Sample Explanation
For the first test case, there are two islands, distinguished by different digits below:
01111
11001
10201
10001
11111
Island 2 is inside the “cycle” of island 1, so island 2 is a sub-island of island 1. The answer is .
For the second test case, there are three islands, distinguished by different digits below:
111111
100001
020301
100001
111111
Note that island 3 is not a sub-island of island 1 or island 2, because neither island 1 nor island 2 has a “cycle”.
Constraints
For of the test cases, .
For of the test cases, , .
Lanqiao Cup 2023 Provincial Contest B Group, Problem F.
Translated by ChatGPT 5