breadth first traversal python program

Solutions on MaxInterview for breadth first traversal python program by the best coders in the world

showing results for - "breadth first traversal python program"
Manuela
15 Jul 2020
1class Graph:
2    def __init__(self):
3        # dictionary containing keys that map to the corresponding vertex object
4        self.vertices = {}
5 
6    def add_vertex(self, key):
7        """Add a vertex with the given key to the graph."""
8        vertex = Vertex(key)
9        self.vertices[key] = vertex
10 
11    def get_vertex(self, key):
12        """Return vertex object with the corresponding key."""
13        return self.vertices[key]
14 
15    def __contains__(self, key):
16        return key in self.vertices
17 
18    def add_edge(self, src_key, dest_key, weight=1):
19        """Add edge from src_key to dest_key with given weight."""
20        self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
21 
22    def does_edge_exist(self, src_key, dest_key):
23        """Return True if there is an edge from src_key to dest_key."""
24        return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
25 
26    def __iter__(self):
27        return iter(self.vertices.values())
28 
29 
30class Vertex:
31    def __init__(self, key):
32        self.key = key
33        self.points_to = {}
34 
35    def get_key(self):
36        """Return key corresponding to this vertex object."""
37        return self.key
38 
39    def add_neighbour(self, dest, weight):
40        """Make this vertex point to dest with given edge weight."""
41        self.points_to[dest] = weight
42 
43    def get_neighbours(self):
44        """Return all vertices pointed to by this vertex."""
45        return self.points_to.keys()
46 
47    def get_weight(self, dest):
48        """Get weight of edge from this vertex to dest."""
49        return self.points_to[dest]
50 
51    def does_it_point_to(self, dest):
52        """Return True if this vertex points to dest."""
53        return dest in self.points_to
54 
55 
56class Queue:
57    def __init__(self):
58        self.items = []
59 
60    def is_empty(self):
61        return self.items == []
62 
63    def enqueue(self, data):
64        self.items.append(data)
65 
66    def dequeue(self):
67        return self.items.pop(0)
68 
69 
70def display_bfs(vertex):
71    """Display BFS Traversal starting at vertex."""
72    visited = set()
73    q = Queue()
74    q.enqueue(vertex)
75    visited.add(vertex)
76    while not q.is_empty():
77        current = q.dequeue()
78        print(current.get_key(), end=' ')
79        for dest in current.get_neighbours():
80            if dest not in visited:
81                visited.add(dest)
82                q.enqueue(dest)
83 
84 
85g = Graph()
86print('Menu')
87print('add vertex <key>')
88print('add edge <src> <dest>')
89print('bfs <vertex key>')
90print('display')
91print('quit')
92 
93while True:
94    do = input('What would you like to do? ').split()
95 
96    operation = do[0]
97    if operation == 'add':
98        suboperation = do[1]
99        if suboperation == 'vertex':
100            key = int(do[2])
101            if key not in g:
102                g.add_vertex(key)
103            else:
104                print('Vertex already exists.')
105        elif suboperation == 'edge':
106            src = int(do[2])
107            dest = int(do[3])
108            if src not in g:
109                print('Vertex {} does not exist.'.format(src))
110            elif dest not in g:
111                print('Vertex {} does not exist.'.format(dest))
112            else:
113                if not g.does_edge_exist(src, dest):
114                    g.add_edge(src, dest)
115                else:
116                    print('Edge already exists.')
117 
118    elif operation == 'bfs':
119        key = int(do[1])
120        print('Breadth-first Traversal: ', end='')
121        vertex = g.get_vertex(key)
122        display_bfs(vertex)
123        print()
124 
125    elif operation == 'display':
126        print('Vertices: ', end='')
127        for v in g:
128            print(v.get_key(), end=' ')
129        print()
130 
131        print('Edges: ')
132        for v in g:
133            for dest in v.get_neighbours():
134                w = v.get_weight(dest)
135                print('(src={}, dest={}, weight={}) '.format(v.get_key(),
136                                                             dest.get_key(), w))
137        print()
138 
139    elif operation == 'quit':
140        break
queries leading to this page
breadthfirstsearch pythonbreadth first search pytonbfs example pythonbreadth first search python treebreadth first search aoj what queue to use for bfs pythonbfs python codebsf alorithim in pythonpython code that implements bfs 28breadth first search 29breadth first search tree pythonbreadth first search or bfs for a graph pythonc 2b 2b graph implementation bfspython breadth first search codeimplementing bfs in pythongraph traversal codeprint breadth first traversal orderbfs in directed graph examplehow to do bfs tree in pythonbreadth first search and depth first search differencebfs using queue in c 2b 2bpython traversre breadth first searchbfs in pythonbreath first search algorithmbreadth search in python nodebfs javapython bfs graphpython program for bfsbsf in pythonbreadth first traversalbread first search python implement bfs algorithm breadth first tree traversal pythonwrite a program to implement breadth first search algorithm using adjacency matriximplement bfs graph in c 2b 2bhow to do bfs in pythonbfs graph pythonbfs in graphfirst breadth search code cpphow to implement bfs in pythonbfs python implementationbreadth first searcg pythonimplement breadth first search using a queue and while looppython program for breadth first search traversal for a graph bfs implementation in pythonbreadth first search python3breadth first search code example pythonbfs using queue in c 2b 2b using adjacency matrixwhen breadth first search is optimalgraph breadth first search pythonbfs code in cppimplement breadth first search algorithmbfs algorithm in pythonbfs function c 2b 2bbreadth first search pythonbfs for graph in pythonbreadth first search python programque data structure bfs for search pyimplement bfs in pythonbfs graphbfs algorithm pythonthe breadth first traversal algorithm is implemented on given graph using queue one of the possible order for visiting node on given graph 3aiterative bfs algorithm pythonwrite a python program to implement breadth first search traversal bfs solutions in c 2b 2bbinary tree breadth first traversal pythonbreadth first search in pythongenerating a graph for bfs pythonhow to do a bfs over a graph pythonbfs python iterativeimplement graph creation and graph traversal using breadth first search 28linked list e2 80 93queue 29when is breadth first search is optimalbreadth first search program in c 2b 2bbfs is used in graph how to do bfs pythonbreadth first search on a tree in pythonbreadth first search algorithm implementation pythonbreadth first search tree python code bfs implementation in javabfs pythonbfs in adjacency matrix pythonbreadth first traversal without recursion pythonbreadth first traversal python graphbreadth first search matrix c 2b 2balgorithm breadth first searchbfs python graphbfs tree pythonbfs program in pythonbreadth first search algorithmbfs template pythonwhich ds is used to perform breadth first search of graphbreadth first implementation in pythonbreadth first search and depth first searchbfs algorithnm in pythonbfs using c 2b 2bpython breadth first searchpython code bfs 28bfs 29 python codebfs bt algorithm pythonjava bfs algorithmbfs source code in javabreadth first search advantagesbreadth first traversal algorithm for treebreadth first traversal of a graph in pythonpython code for bfscreate breadth first search binary tree pythonbfs algorithm implementation in pythonhow to implement breadth first searchbreadth first order c 2b 2bcpp adjacency list bfspython bfs implementationpython graphs breadth first 22traversal 22bfs examplesbreadth first traversal tree pythonpyhtom bfs alogorithm listall valid bfs in pythonbreadth first order using adjacency matrix cbreath first search pythongraph breadth first search using adjacency matrixbreadth first search algorithm python codebfs code in pythonwrite a python program for implementing of bfsbfs code pythoncalculate breadth first traversalpython breadth first search binary treepython bfs searchbfs traversal algorithmbreadth for search pythonbfs pythonbfs examplebsf pythonbreadth first binary tree pythonbfs pseudocode pythonbreadth first algorithm pythonpython breadth first search treeimplement a breadth first searchbreath tree search algorithm in pythonbfs code with graph output pythonbreadth first search python modulewrite bfs pythonare depth first and breadth first search algorithms easier in c 2b 2b or pythonbfs in c 2b 2b using queuebfs code in c 2b 2bbreadth first search in c 2b 2b using adjacency listbfs directed graph c 23breathfirst algorithm to codetree breadth first searchbreadth first search algorithm pythonbfs using pythonqueue using bfsbreadth first searchbreadth first search python treebfr search graph pythonbreadth first traversal graphpython graph bfswhat is bfs in pythonjava breadth firstiterative bft pythionbfs on graph javabreadth first search python implementationbreadth first search for tree in c breadth first search python implementationbreadth first search gfgbreadth first search pythonbfs cppbfs codebfs python code with graph outputpython graphs breadth first traversalbfs search pythonbreadth first search algorithm in pythongraph in python bfsbreadth first search tree traversal pythonbfs algorithm python code bfs pythonbfs using stack or queue in c 2b 2bbfs in javapython breadth first traversalwrite a program for breadth first search traversal for a graph pythonbreadth first pythonbreadth first search algorithm python mazegraphs breadth firs searching in pythonpython recursive breadth first searchgraph bfswidth search algorithmbreadth first search algorithm pythonapply bfs on the graph given below and show all steps breadth first search arraylist mazeimplement breadth first search graph traversal technique on a graph in cbreadth first traversalbreadth first search class pythonwrite a program to implement breadth first search algorithm using queuepython bfs templatebfs using queue in javabfs in python using dictionarypython breadth first search codebfs on graph pythonpython bfsbfs traversal in tree cppbreadth first traversal algorithmhow to do breadth first traversalbreadth first traversal of a tree in cppbreadth first traversal of a tree in cpp adjacency matrixbreadth first graph pythonpython code for breadth first searchbfs with graph argument pythonbreadth search pythongraph create using list and queuebreadth first traversal pythonbreadth first traversal python program