华为7.28提前批笔试

本文探讨了两道编程题目,涉及集合操作、依赖分析、图遍历与路径跟踪。第一题展示了如何利用defaultdict处理列表依赖,第二题则讲解了深度优先搜索和回溯算法在迷宫追踪中的应用。通过实例解析,读者将理解如何在Python中高效解决算法问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一题

第二题

import collections
while True:
    try:
        m = int(input().strip())
        n = int(input().strip())
        z = int(input().strip())
        list_ = []
        depend = [0 for _ in range(m)]
        dict_ = collections.defaultdict(list)
        for i in range(z):
            list_.append(list(map(int, input().strip().split(' '))))
            depend[list_[i][1]-1] += 1
            dict_[list_[i][0]-1].append(list_[i][1]-1)

    except:
        queue = [i for i in range(m) if depend[i] == 0]
        ans = 0
        while queue:
            ans += 1
            for i in range(n):
                if queue:
                    a = queue.pop(0)
                    depend[a] -= 1
                    for value in dict_[a]:
                        depend[value] -= 1
            for j in range(m):
                if j not in queue and depend[j] == 0:
                    queue.append(j)


        print(ans)
        exit()

第三题

def trackback(x,y,path,ans, count, list_):
    if x == des_x and y == des_y:
        if count == num0+1:
            ans.append(list(path))
        return ans
    for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
        if 0 <= x+dx < m and 0 <= y+dy < n and (list_[x+dx][y+dy] == 0 or list_[x+dx][y+dy] == 2):
            list_[x+dx][y+dy] = -1
            count += 1
            path.append((x+dx,y+dy))
            ans = trackback(x+dx, y+dy, path, ans, count, list_)
            path.pop()
            count -= 1
            list_[x+dx][y+dy] = 0
    return ans

while True:
    try:
        m, n = map(int, input().strip().split(' '))
        list_ = []
        num0 = 0
        for i in range(m):
            l = list(map(int, input().strip().split(' ')))
            for j in range(n):
                if l[j] == 0:
                    num0 += 1
                elif l[j] == 1:
                    start_x = i
                    start_y = j
                elif l[j] == 2:
                    des_x = i
                    des_y = j
            list_.append(l)
        ans = []
        path = [(start_x,start_y)]
        ans = trackback(start_x, start_y, path, ans, 0, list_)
        print(ans)
    except:
        exit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值