def find_enclosed_areas(grid):
# 获取网格的尺寸
rows, cols = len(grid), len(grid[0])
# 定义四个方向:上下左右
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def is_valid(x, y):
# 检查坐标是否在网格内
return 0 <= x < rows and 0 <= y < cols
def bfs(start):
# 使用队列进行广度优先搜索
queue = [start]
enclosed = True
region = []
while queue:
x, y = queue.pop(0)
if (x, y) in visited:
continue
visited.add((x, y))
region.append((x, y))
for dx, dy in directions:
nx, ny = x + dx, y + dy
if is_valid(nx, ny):
if grid[nx][ny] == 0:
queue.append((nx, ny))
else:
enclosed = False
return region if enclosed else []
visited = set()
enclosed_areas = []
for i in range(rows):
for j in range(cols):
if grid[i][j] == 0 and (i, j) not in visited:
enclosed_area = bfs((i, j))
if enclosed_area:
enclosed_areas.append(enclosed_area)
return enclosed_areas
# 示例网格:0 代表空白区域,1 代表边界
grid = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1],
]
print(find_enclosed_areas(grid))