深度优先遍历和广度优先遍历求5×5数组地图
时间: 2023-07-13 09:11:46 浏览: 80
好的,下面是一个示例程序,可以使用深度优先遍历和广度优先遍历对一个5x5数组地图进行遍历。
```python
# 定义5x5数组地图
map = [
[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[1, 1, 0, 1, 0],
[0, 1, 0, 0, 0]
]
# 定义深度优先遍历函数
def dfs(map, x, y, visited):
visited.append((x, y))
print("Visited node ({}, {})".format(x, y))
# 检查上方节点
if y > 0 and map[x][y-1] == 1 and (x, y-1) not in visited:
dfs(map, x, y-1, visited)
# 检查左方节点
if x > 0 and map[x-1][y] == 1 and (x-1, y) not in visited:
dfs(map, x-1, y, visited)
# 检查下方节点
if y < len(map[0])-1 and map[x][y+1] == 1 and (x, y+1) not in visited:
dfs(map, x, y+1, visited)
# 检查右方节点
if x < len(map)-1 and map[x+1][y] == 1 and (x+1, y) not in visited:
dfs(map, x+1, y, visited)
# 定义广度优先遍历函数
def bfs(map, x, y, visited):
queue = [(x, y)]
visited.append((x, y))
while queue:
node = queue.pop(0)
print("Visited node ({}, {})".format(node[0], node[1]))
# 检查上方节点
if node[1] > 0 and map[node[0]][node[1]-1] == 1 and (node[0], node[1]-1) not in visited:
queue.append((node[0], node[1]-1))
visited.append((node[0], node[1]-1))
# 检查左方节点
if node[0] > 0 and map[node[0]-1][node[1]] == 1 and (node[0]-1, node[1]) not in visited:
queue.append((node[0]-1, node[1]))
visited.append((node[0]-1, node[1]))
# 检查下方节点
if node[1] < len(map[0])-1 and map[node[0]][node[1]+1] == 1 and (node[0], node[1]+1) not in visited:
queue.append((node[0], node[1]+1))
visited.append((node[0], node[1]+1))
# 检查右方节点
if node[0] < len(map)-1 and map[node[0]+1][node[1]] == 1 and (node[0]+1, node[1]) not in visited:
queue.append((node[0]+1, node[1]))
visited.append((node[0]+1, node[1]))
# 使用深度优先遍历遍历地图
visited = []
for i in range(len(map)):
for j in range(len(map[0])):
if map[i][j] == 1 and (i, j) not in visited:
print("\nStarting DFS from node ({}, {})".format(i, j))
dfs(map, i, j, visited)
# 使用广度优先遍历遍历地图
visited = []
for i in range(len(map)):
for j in range(len(map[0])):
if map[i][j] == 1 and (i, j) not in visited:
print("\nStarting BFS from node ({}, {})".format(i, j))
bfs(map, i, j, visited)
```
该程序定义了深度优先遍历函数和广度优先遍历函数,可以分别使用这两个函数遍历一个5x5数组地图。在遍历过程中,程序会输出已经访问过的节点坐标。
在主程序中,首先使用深度优先遍历遍历地图,然后使用广度优先遍历遍历地图。对于每个起始节点,程序会输出 "Starting DFS/BFS from node (x, y)",表示从该节点开始进行深度优先遍历或广度优先遍历。
阅读全文