-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23.py
100 lines (92 loc) · 2.69 KB
/
23.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
with open("23.txt", "r") as f:
lines = f.read().split("\n")
map = [list(line) for line in lines]
m, n = len(map), len(map[0])
for j in range(n):
if map[0][j] == ".":
start_j = j
break
for j in range(n):
if map[m - 1][j] == ".":
end_j = j
break
D = {
">": (0, 1),
"<": (0, -1),
"v": (1, 0),
"^": (-1, 0)
}
import sys
sys.setrecursionlimit(10_000)
# cands = []
# def dfs(i, j, seen=set([(0, start_j)])):
# if i == m - 1 and j == end_j:
# cands.append(len(seen) - 1)
# return
# if map[i][j] == ".":
# d = list(D.values())
# else:
# d = [D[map[i][j]]]
# for di, dj in d:
# ii, jj = i + di, j + dj
# if 0 <= ii < m and 0 <= jj < n and map[ii][jj] != "#" and (ii, jj) not in seen:
# seen.add((ii, jj))
# dfs(ii, jj)
# seen.remove((ii, jj))
# dfs(0, start_j)
# print(max(cands))
from collections import defaultdict
G = defaultdict(set)
intersections = set()
for i in range(m):
for j in range(n):
if map[i][j] == "#":
continue
poss = []
for di, dj in list(D.values()):
ii, jj = i + di, j + dj
if 0 <= ii < m and 0 <= jj < n and map[ii][jj] != "#":
poss.append((di, dj))
if len(poss) == 2:
continue
intersections.add((i, j))
for i, j in intersections:
if map[i][j] == "#":
continue
for di, dj in list(D.values()):
ii, jj = i + di, j + dj
if 0 <= ii < m and 0 <= jj < n and map[ii][jj] != "#":
cnt = 1
curi, curj, previ, prevj = ii, jj, i, j
while True:
if (curi, curj) in intersections:
break
for dcuri, dcurj in list(D.values()):
newi, newj = curi + dcuri, curj + dcurj
if newi == previ and newj == prevj:
continue
if 0 <= newi < m and 0 <= newj < n and map[newi][newj] != "#":
cnt += 1
previ, prevj = curi, curj
curi, curj = newi, newj
break
G[(i, j)].add((curi, curj, cnt))
# for k, v in G.items():
# print(k, v)
cands = []
weights = []
def dfs(i, j, seen=set([(0, start_j)])):
if i == m - 1 and j == end_j:
cands.append(sum(weights))
return
for ii, jj, w in G[(i, j)]:
if (ii, jj) not in seen:
seen.add((ii, jj))
# seen.append((ii, jj))
weights.append(w)
dfs(ii, jj)
weights.pop()
# seen.pop()
seen.remove((ii, jj))
dfs(0, start_j)
print(max(cands))