这个问题可以通过深度优先搜索(DFS)或广度优先搜索(BFS)来解决。我们需要遍历整个网格,每当遇到一个未被访问过的陆地(1),就进行DFS或BFS来标记所有相邻的陆地,这样就能统计出独立的领地数量。 解决方案代码 ```python def count_territories(grid): if not grid: return 0 rows = len(grid) cols = len(grid[0]) count = 0 for i in range(rows): for j in range(cols): if grid[i][j] == 1: count += 1 dfs(grid, i, j, rows, cols) return count def dfs(grid, i, j, rows, cols): if i < 0 or j < 0 or i >= rows or j >= cols or grid[i][j] != 1: return grid[i][j] = 0 # Mark as visited # Explore all four directions dfs(grid, i + 1, j, rows, cols) dfs(grid, i - 1, j, rows, cols) dfs(grid, i, j + 1, rows, cols) dfs(grid, i, j - 1, rows, cols) # Read input n, m = map(int, input().split()) grid = [] for _ in range(n): row = list(map(int, input().split())) grid.append(row) # Calculate and print the number of territories print(count_territories(grid)) ``` 代码解释 1. count_territories函数:主函数,负责遍历网格,每当发现未被访问的陆地(1)时,增加领地计数并调用DFS来标记所有相连的陆地。 2. dfs函数:递归函数,用于深度优先搜索。将当前陆地标记为已访问(0),然后递归检查上下左右的相邻区域。 3. 输入处理:读取网格的行数和列数,然后逐行读取网格数据。 4. 输出结果:调用`count_territories`函数计算领地数量并输出。 需要注意的逻辑点 - 确保在DFS过程中检查数组边界,避免越界访问。 - 标记已访问的陆地时,直接修改原数组,无需额外空间。 - 领地计数仅在遇到未被访问的陆地时增加,确保每个领地只计数一次。 [2025-03-29 10:17:46 | AI写代码神器 | 515点数解答]