* cycle var mi bakan code yaz. testini de yap. testisini de.

This commit is contained in:
Eray Özkural
2005-07-18 13:11:39 +00:00
parent a2fe2361a4
commit ee6e59f9d9
2 changed files with 22 additions and 10 deletions
+16 -4
View File
@@ -1,5 +1,8 @@
# the most simple minded digraph class ever # the most simple minded digraph class ever
class CycleError:
pass
class digraph(object): class digraph(object):
def __init__(self): def __init__(self):
@@ -66,7 +69,7 @@ class digraph(object):
self.d = {} self.d = {}
self.f = {} self.f = {}
for u in self.__v: for u in self.__v:
self.color[u] = 'w' self.color[u] = 'w' # mark white (unexplored)
self.p[u] = None self.p[u] = None
self.time = 0 self.time = 0
for u in self.__v: for u in self.__v:
@@ -74,17 +77,26 @@ class digraph(object):
self.dfs_visit(u, finish_hook) self.dfs_visit(u, finish_hook)
def dfs_visit(self, 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 self.d[u] = self.time = self.time + 1
for v in self.adj(u): for v in self.adj(u):
if self.color[v] == 'w': if self.color[v] == 'w': # explore unexplored vertices
self.p[v] = u self.p[v] = u
self.dfs_visit(v, finish_hook) 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: if finish_hook:
finish_hook(u) finish_hook(u)
self.f[u] = self.time = self.time + 1 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): def topological_sort(self):
l = [] l = []
self.dfs(lambda u: l.append(u)) self.dfs(lambda u: l.append(u))
+6 -6
View File
@@ -7,15 +7,15 @@ from pisi.config import config
class GraphTestCase(unittest.TestCase): class GraphTestCase(unittest.TestCase):
def setUp(self): def setUp(self):
g0 = graph.digraph() self.g0 = graph.digraph()
g0.from_list([ (1,2), (1,3), (2,3), (3,4), (4, 5), (4,1)]) self.g0.from_list([ (1,2), (1,3), (2,3), (3,4), (4, 5), (4,1)])
g1 = graph.digraph() self.g1 = graph.digraph()
g1.from_list([ (0,2), (0,3), (3,4), (2,4), (0,5), (5,4) ]) self.g1.from_list([ (0,2), (0,3), (3,4), (2,4), (0,5), (5,4) ])
self.g1 = g1
def testCycle(self): def testCycle(self):
pass self.assert_(not self.g0.cycle_free())
self.assert_(self.g1.cycle_free())
def testTopologicalSort(self): def testTopologicalSort(self):
order = self.g1.topological_sort() order = self.g1.topological_sort()