Skip to content

Commit f653863

Browse files
authored
Update Graph2.cpp
1 parent 805488e commit f653863

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Topic/Solution/Graph2.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,33 @@ class Solution {
3434
return ans;
3535
}
3636
};
37+
38+
39+
40+
41+
/*
42+
43+
Alternate solution : Graph colouring
44+
45+
*/
46+
47+
48+
class Solution(object):
49+
def eventualSafeNodes(self, graph):
50+
WHITE, GRAY, BLACK = 0, 1, 2
51+
color = collections.defaultdict(int)
52+
53+
def dfs(node):
54+
if color[node] != white:
55+
return color[node] == BLACK
56+
57+
color[node] = GRAY
58+
for nei in graph[node]:
59+
if color[nei] == BLACK:
60+
continue
61+
if color[nei] == GRAY or not dfs(nei):
62+
return False
63+
color[node] = BLACK
64+
return True
65+
66+
return filter(dfs, range(len(graph)))

0 commit comments

Comments
 (0)