Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- with open("2023_17input.txt", 'r') as file:
- my_input = file.read()
- raw_data = my_input
- grid = raw_data.split('\n')
- start_position = (0, 0)
- end_position = (len(grid[0]) - 1, len(grid) - 1)
- ways = {
- 'r': (1, 0),
- 'd': (0, 1),
- 'l': (-1, 0),
- 'u': (0, -1),
- }
- min_cooling = len(grid) * len(grid[0]) * 9
- def add_pos(a, b):
- return tuple([x+y for x, y in zip(a, b)])
- def find_cooling(x, y):
- return int(grid[y][x])
- def vet_way(way, pos, lastmoves):
- # possible objections:
- # - being the eleventh in a row that's the same
- if lastmoves:
- if len(lastmoves) == 10 and lastmoves[-1] == way:
- return False
- # - not having gone four moves in the same direction yet
- elif len(lastmoves) < 4 and lastmoves[-1] != way:
- return False
- # - going back on yourself
- if add_pos(ways[way], ways[lastmoves[-1]]) == (0, 0):
- return False
- new_pos = add_pos(ways[way], pos)
- # - going out of bounds
- if new_pos[0] < 0 or new_pos[0] > len(grid[0]) - 1:
- return False
- if new_pos[1] < 0 or new_pos[1] > len(grid) - 1:
- return False
- return True
- # make massive dictionary of every possible travel state at every position
- records = {}
- for y in range(len(grid)):
- for x in range(len(grid[0])):
- for i in range(1, 11):
- for way in ways:
- records[((x, y), way*i)] = min_cooling
- records[((start_position), "")] = 0
- # start at the starting point with count 0 and no moves made
- changes = {(start_position, "")}
- while changes:
- print(len(changes))
- new_changes = set()
- for pos, lastmoves in changes:
- if pos == end_position:
- pass
- else:
- for way in ways:
- if vet_way(way, pos, lastmoves):
- new_pos = add_pos(pos, ways[way])
- newcooling = records[(pos, lastmoves)] + find_cooling(*new_pos)
- if way in lastmoves:
- next_moves = lastmoves + way
- else:
- next_moves = way
- if records[(new_pos, next_moves)] > newcooling:
- new_changes.add((new_pos, next_moves))
- records[(new_pos, next_moves)] = newcooling
- changes = new_changes
- for record in records:
- # remember to make sure you've done at least four moves
- # in the current direction, otherwise test input 2 fails
- if record[0] == end_position and len(record[1]) > 3:
- if records[record] < min_cooling:
- min_cooling = records[record]
- print(min_cooling)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement