Skip to content

solves Count Unreachable Pairs of Nodes in an Undirected Graph (#2316) in python #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions python/count_unreachable_pair_of_node_in_an_undirectable_graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/description/
# T: O(N + E) where N is the number of nodes and E is the number of edges
# S: O(N + E) where N is the number of nodes and E is the number of edges

from collections import defaultdict
class Solution:
def __init__(self):
self.graph = defaultdict(list)
self.visited = set()
self.n = 0

def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)

def dfs(self, v, component):
self.visited.add(v)
component.append(v)
for neighbor in self.graph[v]:
if neighbor not in self.visited:
self.dfs(neighbor, component)

def find_components(self):
components = []
for v in range(self.n):
if v not in self.visited:
component = []
self.dfs(v, component)
components.append(component)

return components

def countPairs(self, n, edges):
for u, v in edges:
self.add_edge(u, v)
self.n = n
component_lengths = []
components = self.find_components()
for component in components:
component_lengths.append(len(component))
print(components, component_lengths)

k = sum(component_lengths)
sol = 0
for l in component_lengths:
sol+=((k-l)*l)
sol = sol//2

return sol
26 changes: 26 additions & 0 deletions python/reorder_routes_to_make_all_paths_lead_to_city_zero.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/description/
# T: O(N) where N is the number of nodes in the graph
# S: O(N) where N is the number of nodes in the graph

class Solution:
def __init__(self):
self.reorders = 0

def minReorder(self, n, connections):
edges = {(u, v) for u, v in connections}
graph = {i:[] for i in range(n)}
for u, v in connections:
graph[u].append(v)
graph[v].append(u)
visit = set()
visit.add(0)
def dfs(graph, edges, visit, city):
for node in graph[city]:
if node in visit:
continue
if (node, city) not in edges:
self.reorders+=1
visit.add(node)
dfs(graph, edges, visit, node)
dfs(graph, edges, visit, 0)
return self.reorders