Skip to content

Instantly share code, notes, and snippets.

@zaaath
Created February 23, 2020 04:24
Show Gist options
  • Save zaaath/15697ae98f5fcb985fb0334893be441f to your computer and use it in GitHub Desktop.
Save zaaath/15697ae98f5fcb985fb0334893be441f to your computer and use it in GitHub Desktop.
from collections import deque
class Solution:
def bfsNodes(n: int, adj_list: List[List[int]]) -> int:
if len(adj_list[0]) == 0:
return 0
visited = set()
q = deque([0])
while q:
curr_node = q.pop()
visited.add(curr_node)
for conn_node in adj_list[curr_node]:
if conn_node not in visited:
q.append(conn_node)
return len(visited)
def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
critical_conns = []
# 1. remove one connection
for removed_conn in connections:
# 2. create adj list
adj_list = [[] for _ in range(n)]
for conn in connections:
if conn != removed_conn:
adj_list[conn[0]].append(conn[1])
adj_list[conn[1]].append(conn[0])
# 3. run bfs, calculate number of distinct visited nodes;
# if less than n, this is a critical connection
visited_number = self.bfsNodes(adj_list)
if visited_number < n:
critical_conns.append(removed_conn)
return critical_conns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment