Skip to content

Commit 603af80

Browse files
authored
Create count-unreachable-pairs-of-nodes-in-an-undirected-graph.py
1 parent eb7563e commit 603af80

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# flood fill, bfs, math
5+
class Solution(object):
6+
def countPairs(self, n, edges):
7+
"""
8+
:type n: int
9+
:type edges: List[List[int]]
10+
:rtype: int
11+
"""
12+
def bfs(adj, u, lookup):
13+
q = [u]
14+
lookup[u] = 1
15+
result = 1
16+
while q:
17+
new_q = []
18+
for u in q:
19+
for v in adj[u]:
20+
if lookup[v]:
21+
continue
22+
lookup[v] = 1
23+
result += 1
24+
new_q.append(v)
25+
q = new_q
26+
return result
27+
28+
adj = [[] for _ in xrange(n)]
29+
for u, v in edges:
30+
adj[u].append(v)
31+
adj[v].append(u)
32+
lookup = [0]*n
33+
result = 0
34+
for u in xrange(n):
35+
if lookup[u]:
36+
continue
37+
cnt = bfs(adj, u, lookup)
38+
result += cnt*(n-cnt)
39+
n -= cnt
40+
return result

0 commit comments

Comments
 (0)