FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/sort/top_sort.py at master · ivan1911/algorithms-python · GitHub
ivan1911
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
sort
/
top_sort.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
66 lines (59 loc) · 1.78 KB
Breadcrumbs
algorithms-python
/
algorithms
/
sort
/
top_sort.py
Copy path
File metadata and controls
66 lines (59 loc) · 1.78 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
GRAY
,
BLACK
=
0
,
1
def
top_sort_recursive
(
graph
):
""" Time complexity is the same as DFS, which is O(V + E)
Space complexity: O(V)
"""
order
,
enter
,
state
=
[],
set
(
graph
), {}
def
dfs
(
node
):
state
[
node
]
=
GRAY
#print(node)
for
k
in
graph
.
get
(
node
, ()):
sk
=
state
.
get
(
k
,
None
)
if
sk
==
GRAY
:
raise
ValueError
(
"cycle"
)
if
sk
==
BLACK
:
continue
enter
.
discard
(
k
)
dfs
(
k
)
order
.
append
(
node
)
state
[
node
]
=
BLACK
while
enter
:
dfs
(
enter
.
pop
())
return
order
def
top_sort
(
graph
):
""" Time complexity is the same as DFS, which is O(V + E)
Space complexity: O(V)
"""
order
,
enter
,
state
=
[],
set
(
graph
), {}
def
is_ready
(
node
):
lst
=
graph
.
get
(
node
, ())
if
len
(
lst
)
==
0
:
return
True
for
k
in
lst
:
sk
=
state
.
get
(
k
,
None
)
if
sk
==
GRAY
:
raise
ValueError
(
"cycle"
)
if
sk
!=
BLACK
:
return
False
return
True
while
enter
:
node
=
enter
.
pop
()
stack
=
[]
while
True
:
state
[
node
]
=
GRAY
stack
.
append
(
node
)
for
k
in
graph
.
get
(
node
, ()):
sk
=
state
.
get
(
k
,
None
)
if
sk
==
GRAY
:
raise
ValueError
(
"cycle"
)
if
sk
==
BLACK
:
continue
enter
.
discard
(
k
)
stack
.
append
(
k
)
while
stack
and
is_ready
(
stack
[
-
1
]):
node
=
stack
.
pop
()
order
.
append
(
node
)
state
[
node
]
=
BLACK
if
len
(
stack
)
==
0
:
break
node
=
stack
.
pop
()
return
order
Back
|
FazBrowse Home
|
New Git URL