Skip to content

Commit

Permalink
add cycle
Browse files Browse the repository at this point in the history
  • Loading branch information
shellfly committed Apr 2, 2018
1 parent 5fbce34 commit cfc1bdf
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 11 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ Try to keep the interface and variable name consistent with the original book wh
* [DepthFirstPaths](algs4/depth_first_paths.py)
* [BreadthFirstPaths](algs4/breadth_first_paths.py)
* [CC](algs4/cc.py)
* [Cycle](algs4/cycle.py)

* 5 STRING

Expand Down
8 changes: 4 additions & 4 deletions algs4/depth_first_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,20 @@
class DepthFirstPaths:

def __init__(self, G, s):
self._marked = [False for _ in range(G.V)]
self.marked = [False for _ in range(G.V)]
self.edge_to = [0 for _ in range(G.V)]
self.s = s
self.dfs(G, s)

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

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

def path_to(self, v):
if not self.has_path_to(v):
Expand Down
11 changes: 4 additions & 7 deletions algs4/depth_first_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,17 @@
class DepthFirstSearch:

def __init__(self, G, s):
self._marked = [False for _ in range(G.V)]
self.marked = [False for _ in range(G.V)]
self.count = 0
self.dfs(G, s)

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

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

if __name__ == '__main__':
import sys
print(sys.argv)
Expand All @@ -48,7 +45,7 @@ def marked(self, s):
g.add_edge(v, w)
search = DepthFirstSearch(g, s)
for v in range(g.V):
if search.marked(v):
if search.marked[v]:
print(str(v) + " ")
if search.count == g.V:
print("connected")
Expand Down

0 comments on commit cfc1bdf

Please sign in to comment.