代码如下:
import sys
def dfs(pos_x, pos_y, row_num, col_num, route):
"""
深度优先搜索函数,用于在网格中查找路径。
参数:
pos_x, pos_y: 当前位置的坐标。
row_num, col_num: 当前行和列的访问次数列表。
route: 当前路径上的格子编号列表。
返回:
None
"""
if pos_x == endx and pos_y == endy and row_num == row and col_num == col:
# 如果到达目标位置且行和列的访问次数都满足要求,则打印路径并退出程序
print(*route, sep=' ')
sys.exit()
# 剪枝
for i in zip(row_num, row):
if i[0] > i[1]:
return
for i in zip(col_num, col):
if i[0] > i[1]:
return
# 边界条件,检查当前位置是否越界
if pos_x < 0 or pos_x > n - 1 or pos_y < 0 or pos_y > n - 1:
return
# 尝试四个方向移动
for i in range(4):
tx, ty = pos_x + dirs[i][0], pos_y + dirs[i][1]
# 检查下一个位置是否在网格内且未被访问过
if 0 <= tx < n and 0 <= ty < n and vis[tx][ty] == 0:
# 标记下一个位置为已访问
vis[tx][ty] = 1
# 更新行和列的访问次数
row_num[ty] += 1
col_num[tx] += 1
# 将下一个位置的编号添加到路径中
route.append(road[tx][ty])
# 递归调用DFS函数,继续搜索
dfs(tx, ty, row_num, col_num, route)
# 回溯,撤销之前的操作
route.pop()
row_num[ty] -= 1
col_num[tx] -= 1
vis[tx][ty] = 0
return
# 输入网格大小
n = int(input())
# 输入每行和每列的最大访问次数
row = list(map(int, input().split()))
col = list(map(int, input().split()))
# 初始化访问状态数组,并标记起始位置为已访问
vis = [[0] * n for i in range(n)]
vis[0][0] = 1
# 初始化不同的移动方向
dirs = [[0, -1], [0, 1], [-1, 0], [1, 0]]
# 初始化网格中的路径编号
road = [[0] * n for i in range(n)]
val = 0
for i in range(n):
for j in range(n):
road[i][j] = val
val += 1
# 设置起始和结束位置
startx, starty, endx, endy = 0, 0, n - 1, n - 1
# 从起始位置开始DFS搜索(将起始个位置先添加进来)
dfs(startx, starty, [1] + [0] * (n - 1), [1] + [0] * (n - 1), [0])
7个案例只通过了6个,最后一个超时了,有更好的剪枝方法欢迎评论区讨论哦。