求助:Advent of Code 2023 Day17 Part2代码测通但输入报错
Advent of Code 2023 第17天第二部分代码排查请求
我在解决Advent of Code 2023第17天第二部分问题时,第一部分能得到正确答案,但修改代码适配第二部分规则后,针对实际输入的答案错误,不过代码能通过题目提供的测试用例,实在找不到问题所在。
可能的问题排查方向
- 初始状态仅添加了朝右的节点,缺少朝下的初始节点,可能导致错过更优路径
closed集合的去重逻辑存在缺陷:仅用(y, x, 方向, 连续步数)判断是否访问过,但同一状态可能存在更小的代价路径,直接跳过会导致最优解被忽略,应该改用字典记录每个状态的最小代价- 转向规则验证:检查
expand_helper中转向时是否严格执行了"必须连续走满4步才能转向"的要求,是否存在提前转向的情况
以下是我的代码:
from copy import deepcopy from heapq import heappush, heappop pInput = [ [int(char) for char in list(line.replace("\n", ""))] for line in open("input.txt", "r") ] width, height = len(pInput[0]), len(pInput) def maxStepsReached(steps): return steps > 10 def isOOB(y, x): return not (0 <= y < len(pInput) and 0 <= x < len(pInput[0])) def expand_helper(node, dy, dx, dir, res): new_y = node[1] + dy new_x = node[2] + dx if isOOB(new_y, new_x) or dir == node[3] and maxStepsReached(node[4] + 1): return res if dir == node[3]: res.append((node[0] + pInput[new_y][new_x], new_y, new_x, dir, node[4] + 1)) elif node[4] >= 4: res.append((node[0] + pInput[new_y][new_x], new_y, new_x, dir, 1)) return res def expand(node): res = [] if node[3] == ">": for dy, dx, dir in [[0, 1, ">"], [-1, 0, "A"], [1, 0, "V"]]: res = expand_helper(node, dy, dx, dir, res) elif node[3] == "<": for dy, dx, dir in [[0, -1, "<"], [-1, 0, "A"], [1, 0, "V"]]: res = expand_helper(node, dy, dx, dir, res) elif node[3] == "A": for dy, dx, dir in [[-1, 0, "A"], [0, 1, ">"], [0, -1, "<"]]: res = expand_helper(node, dy, dx, dir, res) elif node[3] == "V": for dy, dx, dir in [[1, 0, "V"], [0, 1, ">"], [0, -1, "<"]]: res = expand_helper(node, dy, dx, dir, res) return res def ucs(): closed = set() open = [] heappush(open, (0, 0, 0, ">", 1)) while open: node = heappop(open) if node[1] == height - 1 and node[2] == width - 1 and node[4] >= 4: return node[0] if (node[1], node[2], node[3], node[4]) in closed: continue closed.add((node[1], node[2], node[3], node[4])) successors = expand(node) for s in successors: heappush(open, s) return -1 print(ucs())
内容的提问来源于stack exchange,提问作者Coder2002
相关产品推荐
相关产品推荐

