Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- The idea is to use DFS (Depth First Search). In DFS, we follow vertices in tree form called DFS tree. In DFS tree, a vertex u is parent of another vertex v, if v is discovered by u (obviously v is an adjacent of u in graph).
- In DFS tree, a vertex u is articulation point if one of the following two conditions is true.
- 1.u is root of DFS tree and it has at least two children.
- 2.u is not root of DFS tree and it has a child v such that no vertex in subtree rooted with v has a back edge to one of the ancestors (in DFS tree) of u.
- '''
- class Solution:
- #Function to return Breadth First Traversal of given graph.
- def articulationPoints(self, n, adj):
- #ap:articulation point
- parent,disc,low,time,ap,vis=[-1]*n,[1e9]*n,[1e9]*n,0,[False]*n,[False]*n
- def dfs(u):
- nonlocal time
- vis[u]=True
- disc[u]=low[u]=time
- time+=1
- children=0
- for v in adj[u]:
- if vis[v]==False:
- children+=1
- parent[v]=u
- dfs(v)
- low[u]=min(low[v],low[u])
- #condition for root of dfs tree
- if parent[u]==-1 and children>=2:
- ap[u]=True
- #condition for non root disc[u]<=low[v]----->VVIMP
- elif parent[u]!=-1 and disc[u]<=low[v]:
- ap[u]=True
- #already vertices which are not main parent. We need to update low time there
- #low[u]=min(disc[v],low[u]) -------->vvvimp
- elif v!=parent[u]:
- low[u]=min(disc[v],low[u])
- for i in range(n):
- if vis[i]==False:
- dfs(i)
- t=[i for i,j in enumerate(ap) if j==True]
- return t if t else [-1]
- #alternatively we can remove vis array and use disc array as vis array combiningly
- import sys
- sys.setrecursionlimit(10**6)
- class Solution:
- #Function to return Breadth First Traversal of given graph.
- def articulationPoints(self, n, adj):
- parent,disc,low,time,ap=[-1]*n,[-1]*n,[1e9]*n,0,[False]*n
- def dfs(u):
- nonlocal time
- disc[u]=low[u]=time
- time+=1
- children=0
- for v in adj[u]:
- if disc[v]==-1:
- children+=1
- parent[v]=u
- dfs(v)
- low[u]=min(low[v],low[u])
- if parent[u]==-1 and children>=2:
- ap[u]=True
- elif parent[u]!=-1 and disc[u]<=low[v]:
- ap[u]=True
- elif v!=parent[u]:
- low[u]=min(disc[v],low[u])
- for i in range(n):
- if disc[i]==-1:
- dfs(i)
- t=[i for i,j in enumerate(ap) if j==True]
- return t if t else [-1]
Add Comment
Please, Sign In to add comment