鱼C论坛

 找回密码
 立即注册
查看: 3153|回复: 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.

  1. class Solution:
  2.     def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
  3.         graph = [[] for _ in range(n)]
  4.         visitedTime = [0 for _ in range(n)]
  5.         lowTime = [0 for _ in range(n)]
  6.         visited = [False for _ in range(n)]
  7.         result = []
  8.         time = 0
  9.         
  10.         for connection in connections:
  11.             first = connection[0]
  12.             second = connection[1]
  13.             
  14.             graph[first].append(second)
  15.             graph[second].append(first)
  16.         
  17.         
  18.         def dfs(curt: int, parent: int):
  19.             nonlocal time
  20.             visited[curt] = True
  21.             visitedTime[curt] = lowTime[curt] = time
  22.             time += 1
  23.             
  24.             for neighbor in graph[curt]:
  25.                 if neighbor == parent: continue
  26.                     
  27.                 if not visited[neighbor]:
  28.                     dfs(neighbor, curt)
  29.                     lowTime[curt] = min(lowTime[curt], lowTime[neighbor])
  30.                     if visitedTime[curt] < lowTime[neighbor]:
  31.                         result.append([curt, neighbor])
  32.                 else:
  33.                     lowTime[curt] = min(lowTime[curt], visitedTime[neighbor])
  34.                     
  35.         dfs(0, -1)
  36.         return result
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-8 05:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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