def dfs(g, u): """Visit all the nodes of g, starting from u, in a DFS manner""" result = traversal.Traversal(g) dfsVisit(g, u, result) for v in g.nodes(): if not result.isVisited(v): dfsVisit(g, v, result) return result
def bfs(g, u): """Perform a BFS on g starting from u""" discovery = Queue.Queue(maxsize=0) result = traversal.Traversal(g) result.visit(u) for neigh in g.nbrs(u): if result.isUnseen(neigh): result.discover(neigh, u) discovery.put(neigh) while not discovery.empty(): work = discovery.get() result.visit(work) for x in g.nbrs(work): if result.isUnseen(x): result.discover(x, work) discovery.put(x) return result
def __init__(self, sequence): super(CircularSequenceThread, self).__init__(traversal.Traversal(segment.Segment(sequence = X), True) for X in str(sequence))
1. Dijstra only work with positive edge cycle 2. Bellam ford is used to detect negative edge weight cycle in graph 3. If graph is directed make parameter directed=True 4. Input to graph is list of edge weight btw source node to neighbour node # Graph example #http://nptel.ac.in/courses/106103069/Module_8/mst.htm """ x = Create_Graph(l, directed=False) #x.add_edges_to_nodes(b, x.graph) visited = [] import traversal b = traversal.Traversal() b.best_first_search(1, x.graph) b.depth_first_search_recursive(1, x.graph, visited) print("Depth First Search Result\n", format(visited)) from minimum_spanning_tree import MST a = MST() a.prims(x.graph, 1) from single_shortest_path import Dijkstra, bellam_ford Dijkstra(x.graph, 1) bellam_ford(x.graph, 1) from detect_cycle import detect_cycle_in_graph, detect_bipartile_graph detect_cycle_in_graph(x.graph, 1) detect_bipartile_graph(x.graph, 1)
def bfs(g, u): """Perform a BFS on g starting from u""" result = traversal.Traversal(g) # implement the process here bfsVisit(g, u, result) return result