Skip to content

Commit 2da60f3

Browse files
solves Longest Cycle in Graph (#2360) in python
1 parent 482e8c2 commit 2da60f3

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

python/longest_cycle_in_graph.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# https://leetcode.com/problems/longest-cycle-in-a-graph/description/
2+
# T:O(N) where N is the number of nodes in the graph
3+
# S:O(N) where N is the number of nodes in the graph
4+
5+
class Solution:
6+
def __init__(self):
7+
self.answer = -1
8+
9+
def dfs(self, node, edges, dist, visit):
10+
visit[node] = True
11+
neighbor = edges[node]
12+
13+
if neighbor != -1 and not visit[neighbor]:
14+
dist[neighbor] = dist[node] + 1
15+
self.dfs(neighbor, edges, dist, visit)
16+
elif neighbor != -1 and neighbor in dist:
17+
self.answer = max(self.answer, dist[node] - dist[neighbor] + 1)
18+
19+
def longestCycle(self, edges):
20+
n = len(edges)
21+
visit = [False] * n
22+
23+
for i in range(n):
24+
if not visit[i]:
25+
dist = {i: 1}
26+
self.dfs(i, edges, dist, visit)
27+
28+
return self.answer
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/description/
2+
# T: O(N) where N is the number of nodes in the graph
3+
# S: O(N) where N is the number of nodes in the graph
4+
5+
class Solution:
6+
def __init__(self):
7+
self.reorders = 0
8+
9+
def minReorder(self, n, connections):
10+
edges = {(u, v) for u, v in connections}
11+
graph = {i:[] for i in range(n)}
12+
for u, v in connections:
13+
graph[u].append(v)
14+
graph[v].append(u)
15+
visit = set()
16+
visit.add(0)
17+
def dfs(graph, edges, visit, city):
18+
for node in graph[city]:
19+
if node in visit:
20+
continue
21+
if (node, city) not in edges:
22+
self.reorders+=1
23+
visit.add(node)
24+
dfs(graph, edges, visit, node)
25+
dfs(graph, edges, visit, 0)
26+
return self.reorders

0 commit comments

Comments
 (0)