class Graph: def __init__(self): self.vertices = {} self.edges = [] def addEdge(self, f, t): # add them to the list of edges if (f,t) not in self.edges: self.edges.append((f,t)) #add the t vertex to the f vertex's neighnor list self.vertices[f].neighbors.append(t) class Vertex: def __init__(self, key): self.id = key self.neighbors = [] #list of neighbor keys # v is the key of the vertex def BFS(v, searchNode, g): queue = [v] visited = set() while len(queue) > 0: print queue, visited vert = queue.pop(0) if vert == searchNode: return "Node found!" if vert not in visited: queue.extend([w for w in g.vertices[vert].neighbors if w not in visited]) visited.add(vert) return "Not found " graph = {1: [2,4], 2:[3,5], 3: [4,5], 4:[7], 5: [], 7: []} def bfs(graph, start, searchNode): path = [] q = [start] while q: print q v = q.pop(0) if v not in path: path.append(v) q = q + graph[v] return path if __name__ == '__main__': g = Graph() # create vertices for i in range(6): nv = Vertex(i) g.vertices[i] = nv print [g.vertices[v].id for v in g.vertices] # create edges between these vertices g.addEdge(4,0) g.addEdge(4,3) g.addEdge(0,1) g.addEdge(2,1) g.addEdge(3,6) g.addEdge(1,6) print [(f,t) for (f,t) in g.edges] for v in g.vertices: print v, g.vertices[v].neighbors print BFS(4,6,g) """ graph = {1: [2,4], 2:[3,5], 3: [4,5], 4:[7], 5: [], 7: []} print bfs(graph, 1, 4) g2 = {1: [6], 2:[1], 3: [6], 4:[0,3], 0: [1], 6: []} print bfs(g2, 4, 6) """
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question