imashutosh51

Prerequisite Tasks

Jul 31st, 2022 (edited)
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. //checking for circle in directed graph
  2. from collections import defaultdict
  3. def dfs(node, graph, visited):
  4.     if visited[node] == 1:  # currently in recursion stack → cycle
  5.         return False
  6.     if visited[node] == 2:  # already processed
  7.         return True
  8.  
  9.     visited[node] = 1  # mark as visiting
  10.  
  11.     for neighbor in graph[node]:
  12.         if not dfs(neighbor, graph, visited):
  13.             return False
  14.  
  15.     visited[node] = 2  # mark as done
  16.     return True
  17.  
  18.  
  19. # Solution class
  20. class Solution:
  21.     def isPossible(self, n, p,pre):
  22.         # Build adjacency list
  23.         graph = defaultdict(list)
  24.         for a, b in pre:
  25.             graph[b].append(a)
  26.  
  27.         visited = [0] * n  # 0=unvisited, 1=visiting, 2=done
  28.  
  29.         # Run DFS for all nodes
  30.         for i in range(n):
  31.             if visited[i] == 0:
  32.                 if not dfs(i, graph, visited):
  33.                     return False
  34.  
  35.         return True
  36.  
  37.  
  38. '''Method 2-most optmised'''
  39. from collections import deque, defaultdict
  40.  
  41. class Solution:
  42.     def isPossible(self, n, p, arr):
  43.         # Build adjacency list
  44.         graph = defaultdict(list)
  45.         indegree = [0] * n
  46.        
  47.         for a, b in arr:
  48.             graph[b].append(a)
  49.             indegree[a] += 1
  50.  
  51.         # Start with nodes that have indegree 0
  52.         q = deque([i for i in range(n) if indegree[i] == 0])
  53.         count = 0
  54.  
  55.         while q:
  56.             node = q.popleft()
  57.             count += 1
  58.             for neighbor in graph[node]:
  59.                 indegree[neighbor] -= 1
  60.                 if indegree[neighbor] == 0:
  61.                     q.append(neighbor)
  62.  
  63.         # If count == n, all tasks can be completed
  64.         return count == n
Advertisement
Add Comment
Please, Sign In to add comment