下面是一个示例代码,用于遍历一个二维数组并找到“封闭房间”:
def explore_room(grid, row, col, visited):
# 检查当前位置是否在边界内,并且没有被访问过
if (row >= 0 and row < len(grid) and col >= 0 and col < len(grid[0]) and
not visited[row][col]):
# 如果当前位置是空房间,标记为已访问
if grid[row][col] == 0:
visited[row][col] = True
# 递归遍历当前位置的相邻位置
explore_room(grid, row-1, col, visited) # 上
explore_room(grid, row+1, col, visited) # 下
explore_room(grid, row, col-1, visited) # 左
explore_room(grid, row, col+1, visited) # 右
def find_enclosed_rooms(grid):
# 创建一个与二维数组大小相同的visited数组,用于记录是否已访问过
visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
enclosed_rooms = 0
# 遍历二维数组
for i in range(len(grid)):
for j in range(len(grid[i])):
# 如果当前位置是封闭房间,并且没有被访问过
if grid[i][j] == 1 and not visited[i][j]:
# 递归遍历当前位置的相邻位置
explore_room(grid, i, j, visited)
enclosed_rooms += 1
return enclosed_rooms
# 示例用法
grid = [
[1, 0, 1, 1],
[1, 0, 0, 1],
[1, 1, 0, 1],
[1, 0, 1, 1]
]
enclosed_rooms = find_enclosed_rooms(grid)
print(enclosed_rooms) # 输出结果为2,表示有两个封闭房间
这个示例中,find_enclosed_rooms
函数用于遍历二维数组,并调用explore_room
函数来递归地遍历每个封闭房间。explore_room
函数会检查当前位置是否在边界内,并且没有被访问过。如果当前位置是空房间,则标记为已访问,并递归地遍历当前位置的相邻位置。最后,find_enclosed_rooms
函数返回找到的封闭房间的数量。