Created
July 10, 2010 06:31
-
-
Save spoon16/470500 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
class Graph(object): | |
def __init__(self, nodeCount, links): | |
self.nodeCount = nodeCount | |
self.matrix = [[False] * self.nodeCount for _ in range(self.nodeCount)] | |
for l in links: | |
self.matrix[l[0]][l[1]] = self.matrix[l[1]][l[0]] = True | |
def paths(self, path): | |
if not type([]) == type(path): | |
path = [path] | |
c = path[-1] | |
for r in range(self.nodeCount): | |
if not r in path and True == self.matrix[c][r]: | |
path.append(r) | |
self.paths(path) | |
yield path | |
def __str__(self): | |
s = " " | |
for i in range(self.nodeCount): | |
s += str(i) + " " | |
s += "\n" | |
for r in range(self.nodeCount): | |
s += str(r) + " " | |
for c in range(self.nodeCount): | |
s += str(self.matrix[c][r])[0] + " " | |
s += "\n" | |
return s | |
g = Graph(5, [(2,3),(3,4),(4,1),(1,0),(1,3),(0,3)]) | |
print "GRAPH" | |
print g | |
print "PATHS" | |
for p in g.paths(1): | |
print p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment