1.神一样地队友

本文介绍了如何使用Python的deque数据结构和广度优先搜索算法(BFS)来解决一个名为糖果岛的问题,玩家需要在给定的网格中找到一条路径,获取最多的糖果值,避开-1和-2的障碍物。
摘要由CSDN通过智能技术生成

from collections import deque
 
n = int(input())
matrix = [[int(x) for x in input().split()] for _ in range(n)]
candy = [[-1] * n for _ in range(n)]
offsets = [(1, 0), (0, -1), (-1, 0), (0, 1)]
 
queue = deque()
 
for i in range(n):
    for j in range(n):
        if matrix[i][j] == -3:
            candy[i][j] = 0
            queue.append((i, j))
 
ans = -1
 
while queue:
    new_queue = deque()
    flag = False
 
    for pos in queue:
        x, y = pos
 
        for offset in offsets:
            new_x, new_y = x + offset[0], y + offset[1]
 
            if new_x < 0 or new_x >= n or new_y < 0 or new_y >= n or matrix[new_x][new_y] == -1:
                continue
 
            if candy[new_x][new_y] == -1:
                new_queue.append((new_x, new_y))
 
            candy[new_x][new_y] = max(candy[new_x][new_y], candy[x][y] + max(0, matrix[new_x][new_y]))
 
            if matrix[new_x][new_y] == -2:
                ans = candy[new_x][new_y]
                flag = True
 
    if flag:
        break
 
    queue = new_queue
 
print(ans)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值