Skip to content

Instantly share code, notes, and snippets.

@leeacto
Created December 15, 2021 22:23
Show Gist options
  • Save leeacto/99103d5c03be40975ec7ea383ee03d34 to your computer and use it in GitHub Desktop.
Save leeacto/99103d5c03be40975ec7ea383ee03d34 to your computer and use it in GitHub Desktop.
class Node():
def __init__(self, val, pos):
self.pos = pos
self.td = None
self.visited = False
self.val = val
self.nodes = []
def unvisited_nodes(self):
return [n for n in self.nodes if not n.visited]
def __repr__(self):
return str(self.pos)
cave = []
with open('15p.txt', 'r') as f:
for i, line in enumerate(f):
cave.append([Node(int(spot), (i, j)) for j, spot in enumerate(line.strip())])
for i in range(len(cave)):
for j in range(len(cave[0])):
node = cave[i][j]
for k in range(-1, 2):
for l in range(-1, 2):
pos_x = i + k
pos_y = j + l
if (not (k == 0 and l == 0) and
pos_x >= 0 and pos_y >= 0 and
pos_x < len(cave) and pos_y < len(cave[0]) and
abs(k) + abs(l) != 2):
node.nodes.append(cave[pos_x][pos_y])
current = cave[0][0]
current.td = 0
end_node = cave[-1][-1]
while current != end_node:
next_node = None
for node in current.unvisited_nodes():
potential = current.td + node.val
node.td = potential if node.td is None else min(node.td, potential)
if next_node is None or next_node.td > node.td or node == end_node:
next_node = node
current.visited = True
current = next_node
print(current.td)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment