Skip to content

Commit

Permalink
add DirectedDFS
Browse files Browse the repository at this point in the history
  • Loading branch information
shellfly committed May 6, 2018
1 parent 038c00b commit c48fa37
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ Try to keep the interface and variable name consistent with the original book wh
* [SymbolGraph](algs4/symbol_graph.py)
* [DegreesOfSeparation](algs4/degrees_of_separation.py)
* [Digraph](algs4/digraph.py)
* [DirectedDFS](algs4/directed_dfs.py)

* 5 STRING

Expand Down
1 change: 0 additions & 1 deletion algs4/depth_first_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ def dfs(self, G, v):

if __name__ == '__main__':
import sys
print(sys.argv)
f = open(sys.argv[1])
s = int(sys.argv[2])
V = int(f.readline())
Expand Down
56 changes: 56 additions & 0 deletions algs4/directed_dfs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""
Execution: python directed_dfs.py digraph.txt s
Data files: https: // algs4.cs.princeton.edu / 42digraph / tinyDG.txt
https://algs4.cs.princeton.edu/42digraph/mediumDG.txt
https://algs4.cs.princeton.edu/42digraph/largeDG.txt
Determine single-source or multiple-source reachability in a digraph
using depth first search.
Runs in O(E + V) time.
% python directed_dfs.py tinyDG.txt 1
1
% python directed_dfs.py tinyDG.txt 2
0 1 2 3 4 5
% python directed_dfs.py tinyDG.txt 1 2 6
0 1 2 3 4 5 6 8 9 10 11 12
"""

from algs4.digraph import Digraph


class DirectedDFS:

def __init__(self, G, sources):
self._marked = [False for _ in range(G.V)]
for s in sources:
s = int(s)
if not self._marked[s]:
self.dfs(G, s)

def dfs(self, G, v):
self._marked[v] = True
for w in G.adj[v]:
if not self._marked[w]:
self.dfs(G, w)

def marked(self, v):
return self._marked[v]

if __name__ == '__main__':
import sys
f = open(sys.argv[1])
V = int(f.readline())
E = int(f.readline())
g = Digraph(V)
for i in range(E):
v, w = f.readline().split()
g.add_edge(v, w)

reachable = DirectedDFS(g, sys.argv[2:])

for v in range(g.V):
if reachable.marked(v):
print(str(v) + " ")

0 comments on commit c48fa37

Please sign in to comment.