Skip to content

Instantly share code, notes, and snippets.

@spoon16
Created July 10, 2010 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spoon16/470500 to your computer and use it in GitHub Desktop.
Save spoon16/470500 to your computer and use it in GitHub Desktop.
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