-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6.py
107 lines (76 loc) · 2.31 KB
/
6.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
def data(filename):
map = []
for line in open(filename):
map.append(line.strip())
return map
def in_range(map, x, y):
return x in range(len(map)) and y in range(len(map[0]))
def rotate(dx, dy):
# from up to right
if dx == -1:
return 0, 1
# from right to down
if dy == 1:
return 1, 0
# from down to left
if dx == 1:
return 0, -1
# from left to up
if dy == -1:
return -1, 0
def walk(map, x, y, dx, dy):
visited = set()
while in_range(map, x, y):
while in_range(map, x, y) and map[x][y] != '#':
visited.add((x, y))
x += dx
y += dy
if not in_range(map, x, y):
break
x, y = x - dx, y - dy
dx, dy = rotate(dx, dy)
return visited
def get_starting_point(map):
for i in range(len(map)):
for j in range(len(map[0])):
if map[i][j] == '^':
return i, j
def part1(filename):
map = data(filename)
dx, dy = -1, 0
x, y = get_starting_point(map)
visited = walk(map, x, y, dx, dy)
print("Part 1 for ", filename, " is ", len(visited))
def part2(filename):
def is_cycle_with_new_stone(map, x, y, dx, dy, maxmoves):
moves = 0
while in_range(map, x, y):
while in_range(map, x, y) and map[x][y] != '#':
moves += 1
if moves >= 2*maxmoves:
return True
x += dx
y += dy
if not in_range(map, x, y):
break
x, y = x - dx, y - dy
dx, dy = rotate(dx, dy)
return False
map = data(filename)
dx, dy = -1, 0
x, y = get_starting_point(map)
visited = walk(map, x, y, dx, dy)
res = 0
for psx, psy in list(visited):
currx, curry = x, y
currdx, currdy = dx, dy
# Setting a wall in one of the visited points
tempmap = map.copy()
tempmap[psx] = tempmap[psx][:psy] + '#' + tempmap[psx][psy+1:]
if is_cycle_with_new_stone(tempmap, currx, curry, currdx, currdy, len(visited)):
res += 1
print("Part 2 for ", filename, " is ", res)
part1("data/6demo.txt")
part1("data/6.txt")
part2("data/6demo.txt")
part2("data/6.txt")