鱼C论坛

 找回密码
 立即注册
查看: 2516|回复: 0

[学习笔记] Leetcode 1192. Critical Connections in a Network

[复制链接]
发表于 2020-9-16 06:26:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
There are n servers numbered from 0 to n-1 connected by undirected server-to-server connections forming a network where connections[i] = [a, b] represents a connection between servers a and b. Any server can reach any other server directly or indirectly through the network.

A critical connection is a connection that, if removed, will make some server unable to reach some other server.

Return all critical connections in the network in any order.



Example 1:

Screenshot from 2020-09-15 18-24-27.png

Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.


Constraints:

1 <= n <= 10^5
n-1 <= connections.length <= 10^5
connections[i][0] != connections[i][1]
There are no repeated connections.
class Solution:
    def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
        graph = [[] for _ in range(n)]
        visitedTime = [0 for _ in range(n)]
        lowTime = [0 for _ in range(n)]
        visited = [False for _ in range(n)]
        result = []
        time = 0
        
        for connection in connections:
            first = connection[0]
            second = connection[1]
            
            graph[first].append(second)
            graph[second].append(first)
        
        
        def dfs(curt: int, parent: int):
            nonlocal time
            visited[curt] = True
            visitedTime[curt] = lowTime[curt] = time
            time += 1
            
            for neighbor in graph[curt]:
                if neighbor == parent: continue
                    
                if not visited[neighbor]:
                    dfs(neighbor, curt)
                    lowTime[curt] = min(lowTime[curt], lowTime[neighbor])
                    if visitedTime[curt] < lowTime[neighbor]:
                        result.append([curt, neighbor])
                else:
                    lowTime[curt] = min(lowTime[curt], visitedTime[neighbor])
                    
        dfs(0, -1)
        return result

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-7-2 21:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表