forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
detonate-the-maximum-bombs.py
67 lines (64 loc) · 1.96 KB
/
detonate-the-maximum-bombs.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
# Time: O(|V|^2 + |V| * |E|)
# Space: O(|V| + |E|)
# bfs solution
class Solution(object):
def maximumDetonation(self, bombs):
"""
:type bombs: List[List[int]]
:rtype: int
"""
adj = [[] for _ in xrange(len(bombs))]
for i, (xi, yi, ri) in enumerate(bombs):
for j, (xj, yj, _) in enumerate(bombs):
if j == i:
continue
if (xi-xj)**2+(yi-yj)**2 <= ri**2:
adj[i].append(j)
result = 0
for i in xrange(len(bombs)):
q = [i]
lookup = {i}
while q:
new_q = []
for u in q:
for v in adj[u]:
if v in lookup:
continue
lookup.add(v)
new_q.append(v)
q = new_q
result = max(result, len(lookup))
if result == len(bombs):
break
return result
# Time: O(|V|^2 + |V| * |E|)
# Space: O(|V| + |E|)
# dfs solution
class Solution2(object):
def maximumDetonation(self, bombs):
"""
:type bombs: List[List[int]]
:rtype: int
"""
adj = [[] for _ in xrange(len(bombs))]
for i, (xi, yi, ri) in enumerate(bombs):
for j, (xj, yj, _) in enumerate(bombs):
if j == i:
continue
if (xi-xj)**2+(yi-yj)**2 <= ri**2:
adj[i].append(j)
result = 0
for i in xrange(len(bombs)):
stk = [i]
lookup = {i}
while stk:
u = stk.pop()
for v in adj[u]:
if v in lookup:
continue
lookup.add(v)
stk.append(v)
result = max(result, len(lookup))
if result == len(bombs):
break
return result