-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-the-safest-path-in-a-grid.py
179 lines (161 loc) · 6.1 KB
/
find-the-safest-path-in-a-grid.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# Time: O(n^2)
# Space: O(n^2)
class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = self.set[x]
while stk:
self.set[stk.pop()] = x
return x
def union_set(self, x, y):
x, y = self.find_set(x), self.find_set(y)
if x == y:
return False
if self.rank[x] > self.rank[y]: # union by rank
x, y = y, x
self.set[x] = self.set[y]
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
return True
# bfs, bucket sort, union find
class Solution(object):
def maximumSafenessFactor(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs():
dist = [[0 if grid[r][c] == 1 else -1 for c in xrange(len(grid[0]))] for r in xrange(len(grid))]
q = [(r, c) for r in xrange(len(grid)) for c in xrange(len(grid[0])) if grid[r][c]]
d = 0
while q:
new_q = []
for r, c in q:
for dr, dc in DIRECTIONS:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(dist) and 0 <= nc < len(dist[0]) and dist[nr][nc] == -1):
continue
dist[nr][nc] = d+1
new_q.append((nr, nc))
q = new_q
d += 1
return dist
dist = bfs()
buckets = [[] for _ in xrange((len(grid)-1)+(len(grid[0])-1)+1)]
for r in xrange(len(grid)):
for c in xrange(len(grid[0])):
buckets[dist[r][c]].append((r, c))
lookup = [[False]*len(grid[0]) for _ in xrange(len(grid))]
uf = UnionFind(len(grid)*len(grid[0]))
for d in reversed(xrange(len(buckets))):
for r, c in buckets[d]:
for dr, dc in DIRECTIONS:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(dist) and 0 <= nc < len(dist[0]) and lookup[nr][nc] == True):
continue
uf.union_set(nr*len(grid[0])+nc, r*len(grid[0])+c)
lookup[r][c] = True
if uf.find_set(0*len(grid[0])+0) == uf.find_set((len(grid)-1)*len(grid[0])+(len(grid[0])-1)):
break
return d
# Time: O(n^2 * logn)
# Space: O(n^2)
import heapq
# bfs, dijkstra's algorithm
class Solution2(object):
def maximumSafenessFactor(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs():
dist = [[0 if grid[r][c] == 1 else -1 for c in xrange(len(grid[0]))] for r in xrange(len(grid))]
q = [(r, c) for r in xrange(len(grid)) for c in xrange(len(grid[0])) if grid[r][c]]
d = 0
while q:
new_q = []
for r, c in q:
for dr, dc in DIRECTIONS:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(dist) and 0 <= nc < len(dist[0]) and dist[nr][nc] == -1):
continue
dist[nr][nc] = d+1
new_q.append((nr, nc))
q = new_q
d += 1
return dist
def dijkstra(start, target):
max_heap = [(-dist[start[0]][start[1]], start)]
dist[start[0]][start[1]] = -1
while max_heap:
curr, u = heapq.heappop(max_heap)
curr = -curr
if u == target:
return curr
for dr, dc in DIRECTIONS:
nr, nc = u[0]+dr, u[1]+dc
if not (0 <= nr < len(dist) and 0 <= nc < len(dist[0]) and dist[nr][nc] != -1):
continue
heapq.heappush(max_heap, (-min(curr, dist[nr][nc]), (nr, nc)))
dist[nr][nc] = -1
return -1
dist = bfs()
return dijkstra(dist, (0, 0), (len(grid)-1, len(grid[0])-1))
# Time: O(n^2 * logn)
# Space: O(n^2)
import heapq
# bfs, binary search
class Solution3(object):
def maximumSafenessFactor(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs():
dist = [[0 if grid[r][c] == 1 else -1 for c in xrange(len(grid[0]))] for r in xrange(len(grid))]
q = [(r, c) for r in xrange(len(grid)) for c in xrange(len(grid[0])) if grid[r][c]]
d = 0
while q:
new_q = []
for r, c in q:
for dr, dc in DIRECTIONS:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(dist) and 0 <= nc < len(dist[0]) and dist[nr][nc] == -1):
continue
dist[nr][nc] = d+1
new_q.append((nr, nc))
q = new_q
d += 1
return dist
def check(x):
lookup = [[False]*len(dist[0]) for _ in xrange(len(dist))]
q = [(0, 0)]
lookup[0][0] = True
while q:
new_q = []
for r, c in q:
for dr, dc in DIRECTIONS:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(dist) and 0 <= nc < len(dist[0]) and dist[nr][nc] >= x and not lookup[nr][nc]):
continue
lookup[nr][nc] = True
new_q.append((nr, nc))
q = new_q
return lookup[-1][-1]
dist = bfs()
left, right = 0, dist[0][0]
while left <= right:
mid = left + (right-left)//2
if not check(mid):
right = mid-1
else:
left = mid+1
return right