Created
September 30, 2014 15:00
-
-
Save naphthalene/8c7406a23001544088cf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/python | |
from Queue import Queue as Q | |
class UndirectedGraph: | |
def __init__(self, vertices, edges): | |
self.vertices = vertices | |
self.edges = edges | |
if not self.validate_edges(self.edges): | |
print "Invalid Graph" | |
exit(1) | |
def validate_edges(self, edges): | |
for (v1, v2) in edges: | |
if (v1 not in self.vertices or | |
v2 not in self.vertices): | |
return False | |
return True | |
def edges_for_vertex(self, vertex): | |
return map(lambda (v1,v2): v2 if vertex == v1 else v1, | |
filter(lambda (v1,v2): vertex == v1 or vertex == v2, | |
self.edges)) | |
def find_paths(self, start, end): | |
dist = {} | |
count = {} | |
frontier = Q() | |
frontier.put(start) | |
dist[start] = 0 | |
count[start] = 1 | |
while not frontier.empty(): | |
u = frontier.get() | |
if u == end: | |
print "Found {} shortest paths from {} to {}".format( | |
count[u], start, end | |
) | |
print "Processing {}".format(u) | |
for v in self.edges_for_vertex(u): | |
try: | |
# Already visited | |
if dist[v] == dist[u]+1: | |
count[v] = count[v] + count[u] | |
elif dist[v] > dist[u]+1: | |
dist[v] = dist[u] + 1 | |
count[v] = count[u] | |
except KeyError: | |
print "Adding {}".format(v) | |
frontier.put(v) | |
dist[v] = dist[u] + 1 | |
count[v] = count[u] | |
print dist, count | |
def main(): | |
g1 = UndirectedGraph(['A', 'B', 'C', 'D', 'E', "F"], | |
[('A', 'B'), ("D", "E"), | |
("A", "D"), ("C", "E"), | |
("B", "D"), ("B", "E"), | |
("A", "F"), ("F", "E")]) | |
g1.find_paths('A', 'D') # count: 1 | |
g1.find_paths('A', 'C') # count: 3 | |
g1.find_paths('A', 'A') # count: 1 | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment