-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #579 from aishwarya-chandra/day11q1
day11q1
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
``` | ||
class Solution: | ||
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: | ||
n = len(graph) | ||
visited = [False] * n | ||
unsafe = [0] * n | ||
for i in range(n): | ||
if unsafe[i] == 0: | ||
visited[i] = True | ||
self.dfs(i, visited, graph, unsafe) | ||
visited[i] = False | ||
result = [] | ||
for i in range(len(unsafe)): | ||
if unsafe[i] == 1: | ||
result.append(i) | ||
return result | ||
def dfs(self, node: int, visited: List[bool], graph: List[List[int]], unsafe: List[int]) -> bool: | ||
isSafe = True | ||
for neighbor in graph[node]: | ||
if visited[neighbor] or unsafe[neighbor] == 2: | ||
isSafe = False | ||
break | ||
if unsafe[neighbor] == 1: | ||
continue | ||
visited[neighbor] = True | ||
if not self.dfs(neighbor, visited, graph, unsafe): | ||
isSafe = False | ||
visited[neighbor] = False | ||
unsafe[node] = 1 if isSafe else 2 | ||
return isSafe | ||
``` |