LeetCode #1192

Critical Connections in a Network

1개의 풀이 · Python

문제 원문 보기 ↗

SOLUTION INFO

Python · main.py

main.py
class Solution:
    def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:

        # Create the graph
        graph = collections.defaultdict(list)

        for a, b in connections:
            graph[a].append(b)
            graph[b].append(a)

        # Define the properties for Tarjan's algorithm
        idx, lo_link, curr_idx = [None for _ in range(n)], [None for _ in range(n)], 0
        stack, on_stack, unvisited = [], set(), set(range(n))

        # Loop through the unvisited nodes with DFS and find SCC (strongly connected
        # components)
        dfs = [(0, 0)] # Node, predecessor

        while dfs:
            node, predecessor = dfs[-1]
            unvisited.discard(node)

            # Push to stack
            if node not in on_stack:
                stack.append(node)
                on_stack.add(node)

            # Assign the index and low link value
            if idx[node] is None:
                idx[node] = curr_idx
                lo_link[node] = curr_idx
                curr_idx = curr_idx + 1

            # Loop through the neighbors (ignore predecessor)
            for neighbor in graph[node]:
                if neighbor != predecessor:
                    if neighbor in unvisited:
                        dfs.append((neighbor, node))
                        break
                    if neighbor in on_stack:
                        lo_link[node] = min(lo_link[node], lo_link[neighbor])

            # Continue the while loop if there are still neighbors to explore (i. e. top
            # of the DFS stack is different than the current node)
            if dfs[-1][0] != node:
                continue

            # If node is a root node, pop the stack and generate an SCC
            if lo_link[node] == idx[node]:
                while node in on_stack:
                    lo_link[stack[-1]] = lo_link[node]
                    on_stack.remove(stack.pop())

            # This node has been processed (all of its neighbors are visited as well),
			# remove it from the DFS stack
            dfs.pop()

        # Find all the edges that connect different SCCs
        return [[a, b] for a, b in connections if lo_link[a] != lo_link[b]]

SOLUTION DESCRIPTION

풀이 설명

등록된 풀이 설명이 없습니다.

GITHUB COMMUNITY

커뮤니티 평가

GitHub 계정으로 남긴 최신 평가 1건만 반영하며, 데이터는 매일 저장소에 동기화됩니다.

최근 동기화

체감 난이도

아직 평가 없음

첫 난이도 평가를 남겨주세요.

문제 추천

아직 평가 없음

이 문제가 도움이 되었는지 알려주세요.

이 문제 평가하기

GitHub 로그인 후 난이도를 제출하고, 원하는 경우 추천 여부도 함께 남길 수 있습니다.

추천 여부 (선택)

평가하려면 GitHub로 로그인해 주세요.

평가는 자동으로 저장소 Discussion에 기록되므로 Discussion 화면을 직접 열 필요가 없습니다. 같은 문제를 다시 평가하면 기존 평가가 갱신됩니다.

DISCUSSION

댓글

GitHub 로그인 후 작성할 수 있으며 모든 댓글은 이 저장소의 Discussions에 보관됩니다.