蓝桥杯——路径之迷(纯手巧,花了我两小时)

import os
import sys

# 请在此输入您的代码
import os
import sys

# 请在此输入您的代码

res = []
dic = [[-1,0],[0,-1],[1,0],[0,1]]
def dfs(x,y):
    if (num1[x] == 0 or num2[y] == 0 ) and (x <n-1 or y <n-1):
        return False

    pos[x][y] = True
    num1[x]-= 1
    num2[y]-= 1
    res.append(n*x+y)
    if x == n-1 and y == n-1 and num1 == [0]*n and num2 == [0]*n: # 达到终点
        return  True  
    for i,j in dic:
        xx = x+i
        yy = y +j
        if  xx>n-1 or xx<0 or yy <0 or yy>n-1 or pos[xx][yy] or num1[xx] == 0 or num2[yy] == 0:
            continue
        if dfs(x+i,y+j):
            return True
        else:
            pos[xx][yy] = False
            num1[xx]+= 1
            num2[yy]+= 1
            res.pop()
n = int(input())
num2 = list(map(int,input().split()))
num1 = list(map(int,input().split()))

pos = [[False]*n for i in range(n)]
dfs(0,0)
for i in res:# 用for的时间少于直接用内置函数,别问我为什么,实践出真知
    print(i,end = ' ')

# print(' '.join(map(str,res)))

蓝桥杯,路径之迷,深度优先搜索+记忆化+回溯

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值