Created
November 15, 2016 18:38
-
-
Save sumedhe/c5960a2bfd3e59e7bc0e209ce2f065d4 to your computer and use it in GitHub Desktop.
Directed Graph using Dictionary
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
| class Graph: | |
| def __init__(self): | |
| self.dic = {} | |
| def addVertex(self, vert): | |
| if vert not in self.dic: | |
| self.dic[vert] = [] | |
| def addEdge(self, start, end): | |
| if end not in self.dic[start]: | |
| self.dic[start].append(end) | |
| def removeVertex(self, vert): | |
| if vert in self.dic: | |
| for i in self.dic.values(): | |
| if vert in i: | |
| i.remove(vert) | |
| del self.dic[vert] | |
| def findPath(self, start, end, path = []): | |
| path.append(start) | |
| if start == end: | |
| return path | |
| if start not in self.dic: | |
| return None | |
| for node in self.dic[start]: | |
| if node not in path: | |
| newPath = self.findPath(node, end, path) | |
| if newPath: | |
| return newPath | |
| return None | |
| def __str__(self): | |
| s = "" | |
| for i in self.dic: | |
| s += str(i) + " : " + str(self.dic[i]) + "\n" | |
| return s | |
| g = Graph() | |
| g.addVertex(1) | |
| g.addVertex(2) | |
| g.addVertex(3) | |
| g.addVertex(4) | |
| g.addEdge(1,3) | |
| g.addEdge(1,4) | |
| g.addEdge(2,1) | |
| g.addEdge(3,2) | |
| g.addEdge(2,4) | |
| g.addEdge(3,4) | |
| print(g) | |
| print(g.findPath(1,4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment