BFS最后一个点WA,求大佬指点QwQ

P2895 [USACO08FEB] Meteor Shower S

sundowner @ 2024-04-28 20:33:30

代码如下:

from queue import Queue

def star_fall(star: list):
    global farm
    x, y, t = star
    if farm[x][y][1] == -1:
        farm[x][y][0] = 1
        farm[x][y][1] = t
    if x - 1 >= 0 and farm[x - 1][y][1] == -1:
        farm[x - 1][y][0] = 1
        farm[x - 1][y][1] = t
    if y + 1 <= 300 and farm[x][y + 1][1] == -1:
        farm[x][y + 1][0] = 1
        farm[x][y + 1][1] = t
    if x + 1 <= 300 and farm[x + 1][y][1] == -1:
        farm[x + 1][y][0] = 1
        farm[x + 1][y][1] = t
    if y - 1 >= 0 and farm[x][y - 1][1] == -1:
        farm[x][y - 1][0] = 1
        farm[x][y - 1][1] = t

def move(direction: str, start: tuple):
    global farm
    global q
    x = start[0]
    y = start[1]
    t = start[2]
    if direction == "up":
        if x - 1 >= 0 and farm[x - 1][y][2] != 1 and (farm[x - 1][y][0] != 1 or t < farm[x - 1][y][1] - 1):
            farm[x - 1][y][2] = 1
            q.put((x - 1, y, t + 1))
    elif direction == "down":
        if x + 1 <= 300 and farm[x + 1][y][2] != 1 and (farm[x + 1][y][0] != 1 or t < farm[x + 1][y][1] - 1):
            farm[x + 1][y][2] = 1
            q.put((x + 1, y, t + 1))
    elif direction == "left":
        if y - 1 >= 0 and farm[x][y - 1][2] != 1 and (farm[x][y - 1][0] != 1 or t < farm[x][y - 1][1] - 1):
            farm[x][y - 1][2] = 1
            q.put((x, y - 1, t + 1))
    elif direction == "right":
        if y + 1 <= 300 and farm[x][y + 1][2] != 1 and (farm[x][y + 1][0] != 1 or t < farm[x][y + 1][1] - 1):
            farm[x][y + 1][2] = 1
            q.put((x, y + 1, t + 1))
    return

m = int(input())
stars = []
for i in range(m):
    stars.append(list(map(int, input().strip().split())))
stars.sort(key=lambda x: x[2])

farm = [[[0, -1, 0] for _ in range(int(501))] for _ in range(int(501))]  # 是否被击中 什么时候被击中 是否到达过
for i in stars:
    star_fall(i)

ans = -1
q = Queue()
q.put((0, 0, 0))  # x, y, t
farm[0][0][0] = 1

while not q.empty():
    now = q.get()
    if farm[now[0]][now[1]][0] == 0:
        ans = now[2]
        break
    for i in ("up", "down", "left", "right"):
        move(i, now)

print(ans)

只有最后一个测试点WA,我的输出是-1。
本地调试一下发现漫游不出(300, 300),但数据量太大不知道具体是什么情况。
希望有大佬能指出错在哪里了。


by sundowner @ 2024-04-28 20:36:20

数组已经开到(500,500),应该不是数组大小不够的原因。


by zhiyinnitaimeiohbaby @ 2024-05-02 09:41:36

move函数里的第二和第四句判断x+1跟着数组改成<=500,y+1也一样


by zhiyinnitaimeiohbaby @ 2024-05-02 09:42:11

statfall函数一样的问题


by sundowner @ 2024-05-03 17:50:30

@zhiyinnitaimeiohbaby 哦哦哦,谢谢你,是我犯蠢了。非常感谢!


|