* cycle var mi bakan code yaz. testini de yap. testisini de.
This commit is contained in:
+16
-4
@@ -1,5 +1,8 @@
|
||||
# the most simple minded digraph class ever
|
||||
|
||||
class CycleError:
|
||||
pass
|
||||
|
||||
class digraph(object):
|
||||
|
||||
def __init__(self):
|
||||
@@ -66,7 +69,7 @@ class digraph(object):
|
||||
self.d = {}
|
||||
self.f = {}
|
||||
for u in self.__v:
|
||||
self.color[u] = 'w'
|
||||
self.color[u] = 'w' # mark white (unexplored)
|
||||
self.p[u] = None
|
||||
self.time = 0
|
||||
for u in self.__v:
|
||||
@@ -74,17 +77,26 @@ class digraph(object):
|
||||
self.dfs_visit(u, finish_hook)
|
||||
|
||||
def dfs_visit(self, u, finish_hook):
|
||||
self.color[u] = 'g'
|
||||
self.color[u] = 'g' # mark green (discovered)
|
||||
self.d[u] = self.time = self.time + 1
|
||||
for v in self.adj(u):
|
||||
if self.color[v] == 'w':
|
||||
if self.color[v] == 'w': # explore unexplored vertices
|
||||
self.p[v] = u
|
||||
self.dfs_visit(v, finish_hook)
|
||||
self.color[u] = 'b'
|
||||
elif self.color[v] == 'g': # cycle detected
|
||||
raise CycleError
|
||||
self.color[u] = 'b' # mark black (completed)
|
||||
if finish_hook:
|
||||
finish_hook(u)
|
||||
self.f[u] = self.time = self.time + 1
|
||||
|
||||
def cycle_free(self):
|
||||
try:
|
||||
self.dfs()
|
||||
return True
|
||||
except CycleError:
|
||||
return False
|
||||
|
||||
def topological_sort(self):
|
||||
l = []
|
||||
self.dfs(lambda u: l.append(u))
|
||||
|
||||
+6
-6
@@ -7,15 +7,15 @@ from pisi.config import config
|
||||
|
||||
class GraphTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
g0 = graph.digraph()
|
||||
g0.from_list([ (1,2), (1,3), (2,3), (3,4), (4, 5), (4,1)])
|
||||
self.g0 = graph.digraph()
|
||||
self.g0.from_list([ (1,2), (1,3), (2,3), (3,4), (4, 5), (4,1)])
|
||||
|
||||
g1 = graph.digraph()
|
||||
g1.from_list([ (0,2), (0,3), (3,4), (2,4), (0,5), (5,4) ])
|
||||
self.g1 = g1
|
||||
self.g1 = graph.digraph()
|
||||
self.g1.from_list([ (0,2), (0,3), (3,4), (2,4), (0,5), (5,4) ])
|
||||
|
||||
def testCycle(self):
|
||||
pass
|
||||
self.assert_(not self.g0.cycle_free())
|
||||
self.assert_(self.g1.cycle_free())
|
||||
|
||||
def testTopologicalSort(self):
|
||||
order = self.g1.topological_sort()
|
||||
|
||||
Reference in New Issue
Block a user