python breadth first search

# tree level-by-level traversal. O(n) time/space
def breadthFirstSearch(root):
    q = [root]

    while q:
        current = q.pop(0)
        print(current)
        if current.left is not None: q.append(current.left)
        if current.right is not None: q.append(current.right)

4.5
4
Kai 110 points

                                    class Graph:
    def __init__(self):
        # dictionary containing keys that map to the corresponding vertex object
        self.vertices = {}
 
    def add_vertex(self, key):
        """Add a vertex with the given key to the graph."""
        vertex = Vertex(key)
        self.vertices[key] = vertex
 
    def get_vertex(self, key):
        """Return vertex object with the corresponding key."""
        return self.vertices[key]
 
    def __contains__(self, key):
        return key in self.vertices
 
    def add_edge(self, src_key, dest_key, weight=1):
        """Add edge from src_key to dest_key with given weight."""
        self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
 
    def does_edge_exist(self, src_key, dest_key):
        """Return True if there is an edge from src_key to dest_key."""
        return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
 
    def __iter__(self):
        return iter(self.vertices.values())
 
 
class Vertex:
    def __init__(self, key):
        self.key = key
        self.points_to = {}
 
    def get_key(self):
        """Return key corresponding to this vertex object."""
        return self.key
 
    def add_neighbour(self, dest, weight):
        """Make this vertex point to dest with given edge weight."""
        self.points_to[dest] = weight
 
    def get_neighbours(self):
        """Return all vertices pointed to by this vertex."""
        return self.points_to.keys()
 
    def get_weight(self, dest):
        """Get weight of edge from this vertex to dest."""
        return self.points_to[dest]
 
    def does_it_point_to(self, dest):
        """Return True if this vertex points to dest."""
        return dest in self.points_to
 
 
class Queue:
    def __init__(self):
        self.items = []
 
    def is_empty(self):
        return self.items == []
 
    def enqueue(self, data):
        self.items.append(data)
 
    def dequeue(self):
        return self.items.pop(0)
 
 
def display_bfs(vertex):
    """Display BFS Traversal starting at vertex."""
    visited = set()
    q = Queue()
    q.enqueue(vertex)
    visited.add(vertex)
    while not q.is_empty():
        current = q.dequeue()
        print(current.get_key(), end=' ')
        for dest in current.get_neighbours():
            if dest not in visited:
                visited.add(dest)
                q.enqueue(dest)
 
 
g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('bfs <vertex key>')
print('display')
print('quit')
 
while True:
    do = input('What would you like to do? ').split()
 
    operation = do[0]
    if operation == 'add':
        suboperation = do[1]
        if suboperation == 'vertex':
            key = int(do[2])
            if key not in g:
                g.add_vertex(key)
            else:
                print('Vertex already exists.')
        elif suboperation == 'edge':
            src = int(do[2])
            dest = int(do[3])
            if src not in g:
                print('Vertex {} does not exist.'.format(src))
            elif dest not in g:
                print('Vertex {} does not exist.'.format(dest))
            else:
                if not g.does_edge_exist(src, dest):
                    g.add_edge(src, dest)
                else:
                    print('Edge already exists.')
 
    elif operation == 'bfs':
        key = int(do[1])
        print('Breadth-first Traversal: ', end='')
        vertex = g.get_vertex(key)
        display_bfs(vertex)
        print()
 
    elif operation == 'display':
        print('Vertices: ', end='')
        for v in g:
            print(v.get_key(), end=' ')
        print()
 
        print('Edges: ')
        for v in g:
            for dest in v.get_neighbours():
                w = v.get_weight(dest)
                print('(src={}, dest={}, weight={}) '.format(v.get_key(),
                                                             dest.get_key(), w))
        print()
 
    elif operation == 'quit':
        break

4.5 (4 Votes)
0
4
1
Jae C 90 points

                                    #include<iostream>
#include <list>
 
using namespace std;
 


class Graph
{
    int V;   
 
  
    list<int> *adj;   
public:
    Graph(int V);  
 
    
    void addEdge(int v, int w); 
 
    
    void BFS(int s);  
};
 
Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}
 
void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); 
}
 
void Graph::BFS(int s)
{
  
    bool *visited = new bool[V];
    for(int i = 0; i < V; i++)
        visited[i] = false;
 
   
    list<int> queue;
 
   
    visited[s] = true;
    queue.push_back(s);
 
   
    list<int>::iterator i;
 
    while(!queue.empty())
    {
       
        s = queue.front();
        cout << s << " ";
        queue.pop_front();
 
      
        for (i = adj[s].begin(); i != adj[s].end(); ++i)
        {
            if (!visited[*i])
            {
                visited[*i] = true;
                queue.push_back(*i);
            }
        }
    }
}
 

int main()
{
    
    Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);
 
    cout << "Following is Breadth First Traversal "
         << "(starting from vertex 2) \n";
    g.BFS(2);
 
    return 0;
}

4 (1 Votes)
0
4.4
5
Mr Victor 110 points

                                    // BFS algorithm in C

#include <stdio.h>
#include <stdlib.h>
#define SIZE 40

struct queue {
  int items[SIZE];
  int front;
  int rear;
};

struct queue* createQueue();
void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);

struct node {
  int vertex;
  struct node* next;
};

struct node* createNode(int);

struct Graph {
  int numVertices;
  struct node** adjLists;
  int* visited;
};

// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
  struct queue* q = createQueue();

  graph->visited[startVertex] = 1;
  enqueue(q, startVertex);

  while (!isEmpty(q)) {
    printQueue(q);
    int currentVertex = dequeue(q);
    printf("Visited %d\n", currentVertex);

    struct node* temp = graph->adjLists[currentVertex];

    while (temp) {
      int adjVertex = temp->vertex;

      if (graph->visited[adjVertex] == 0) {
        graph->visited[adjVertex] = 1;
        enqueue(q, adjVertex);
      }
      temp = temp->next;
    }
  }
}

// Creating a node
struct node* createNode(int v) {
  struct node* newNode = malloc(sizeof(struct node));
  newNode->vertex = v;
  newNode->next = NULL;
  return newNode;
}

// Creating a graph
struct Graph* createGraph(int vertices) {
  struct Graph* graph = malloc(sizeof(struct Graph));
  graph->numVertices = vertices;

  graph->adjLists = malloc(vertices * sizeof(struct node*));
  graph->visited = malloc(vertices * sizeof(int));

  int i;
  for (i = 0; i < vertices; i++) {
    graph->adjLists[i] = NULL;
    graph->visited[i] = 0;
  }

  return graph;
}

// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
  // Add edge from src to dest
  struct node* newNode = createNode(dest);
  newNode->next = graph->adjLists[src];
  graph->adjLists[src] = newNode;

  // Add edge from dest to src
  newNode = createNode(src);
  newNode->next = graph->adjLists[dest];
  graph->adjLists[dest] = newNode;
}

// Create a queue
struct queue* createQueue() {
  struct queue* q = malloc(sizeof(struct queue));
  q->front = -1;
  q->rear = -1;
  return q;
}

// Check if the queue is empty
int isEmpty(struct queue* q) {
  if (q->rear == -1)
    return 1;
  else
    return 0;
}

// Adding elements into queue
void enqueue(struct queue* q, int value) {
  if (q->rear == SIZE - 1)
    printf("\nQueue is Full!!");
  else {
    if (q->front == -1)
      q->front = 0;
    q->rear++;
    q->items[q->rear] = value;
  }
}

// Removing elements from queue
int dequeue(struct queue* q) {
  int item;
  if (isEmpty(q)) {
    printf("Queue is empty");
    item = -1;
  } else {
    item = q->items[q->front];
    q->front++;
    if (q->front > q->rear) {
      printf("Resetting queue ");
      q->front = q->rear = -1;
    }
  }
  return item;
}

// Print the queue
void printQueue(struct queue* q) {
  int i = q->front;

  if (isEmpty(q)) {
    printf("Queue is empty");
  } else {
    printf("\nQueue contains \n");
    for (i = q->front; i < q->rear + 1; i++) {
      printf("%d ", q->items[i]);
    }
  }
}

int main() {
  struct Graph* graph = createGraph(6);
  addEdge(graph, 0, 1);
  addEdge(graph, 0, 2);
  addEdge(graph, 1, 2);
  addEdge(graph, 1, 4);
  addEdge(graph, 1, 3);
  addEdge(graph, 2, 4);
  addEdge(graph, 3, 4);

  bfs(graph, 0);

  return 0;
}

4.4 (5 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
python graph breadth first search breadth first search python implmementation list breadth first search python bfs traversal in a graph Python code that implements BFS (Breadth-First Search) possible of number BFS traversal from graph bfs and dfs cpp bfs algorithm graph in c bfs traversal algorithm in c c++ bfs algorithm bfs in graph in c++ breadth search algorithm python BFS of graph program in cpp BFS progarm in cpp bfs binary tree c++ c++ program for BFS code bfs on frid cpp code for finding bfs in c++ breadth first search python library bfsutil cpp c program Implementation of Graph traversal - Depth First Search bfs on graph c++ bfs class c++ write a program to implement breadth first search using python stack python using breadth first search simple graph bfs traversal in cpp implementation of bfs in graph in c++ BFS in cp bfs on tree c++ bfs algorithm program c++ bfs tree cpp how to traversing a graph by bfs bfs and dfs graph traversal program in c graph bfs and dfs graph traversal program in c bfs algorithm in cpp bfs algorithm cpp bfs program in c plus plus breadth first tree traversal python breadth first search python tree code implementation of BFS algorithm in c++ code for bfs in c++ traversing graph by bfs breadth first search using python bfs c++ tree bfs code c++ implementing breadth first search in python breadth first search bfs program in python graph traversal bfs question bfs data structure code in c++ bfs graph traversal program in c output given bfs traversal graph bfs traversal of graph in cpp bfs graph traversal program in c a) breadth first search BFS in graph c++ graph representation and breadth first traversal program in c graph bfs c++ python breadth first traversal program in cpp to bfs bfs traversal gfg BFS search for graph traversal algorithm breadth first search tree traversal python python breadth-first search breadth first search source code in python bfs level order traversal graph graph to bfs traversal breadth first traversal of a graph in c bfs traversal of tree ca BFS search C++ bfs traversal of graph gfg bfs in tree in c++ how to find all bfs traversals of a graph implementing a breadth first search in python program to implement BFS algorithm in C++ bfs traversal and dfs traversal graph graph bfs traversal c++ bfs code how to traverse a graph using bfs bfs traversal code c++ bfs traversal code bfs graph c++ Write a C program to traverse the below graph using Depth first traversal and Breadth first traversal bfs code for c++ breath first search in ython bfs tree c++ bfs in tree c++ breadth first search using class python bfs c++ display bfs c++ github Breadth-first Search python code bfs c++ using class bfs algorithm c++ breadth first search path python BFS CP algorithms breadth first implementation in python bfs in c++ using array bfs in c++ code Breadth First Search algorithm on graph python implementation Breadth First Search algorithm python implementation bfs and dfs program in cpp bfs graph traversal example bfs graph traversal c++ graph bfs bfs c++ stl bfc cpp bfs vector c++ bfs code c++ stl bfs algorithm in c++ bfs traversal of grapht bfs algorithm in c++ bfs and dfs in c++ bfs and dfs bfs traversal of a graph bfs on graph cpp breadth first traversal tree python breadth first search python RECU python breadth first seach python breadth first search iterative bfs traversal of tree breadth first search example python breadth-first search in python simple bfs code in c++ two way breadth first search python how to implement breadth first search in python how to make algorithm bfs in cpp methode bfs in cpp python breadth first search breadfirst search breadth first search pythn breadth first search python code bfs in graph in cpp breadth first search implementation python bfs program in data structure using c++ bfs using stl in c++ what is breadth first search python tree breadth first search python bfs in binary tree c++ breadth first search algorithm python example Write a python program to implement Breadth first search Traversal. bfs traversal breadth first searcg python breadthfirst search pyhon bfs and dfs c++ a* graph search example java bfs and dfs in python breadth first search graph java bfs in undirected graph bfs functiojn in python breadth first search python module explain bfs in python breadht first search java Breadth first search on the grahp using linked list ... processing java best implementation for BFS traversing graph bfs c++ code bfs with adjacency list Breadth First Traversal Algorithm BFS undirected graph in JAVA breadth first search in JAVA DFS and BFS programiz breadh first search how to do bfs in java queue using bfs bfs implementation cpp bfs template python e breadth-first search java breadth first search algorithm java graph bfs in python why is bfs implemented using queue bfs algorithm output example bfs algorithm example bfs code gfg breadth first search explained bfs of following graph starting from vertex A bfs of following graph vertex A Breadth-First Graph Search g.LSC_BF() c++ breadth first traversal without recursion python depth first search and breadth first search use of breadth first search Develop a program to implement BFS and DFS traversal of graph bfs algorithm in c BFS implementation in bfs in python in graph Bread First search alogorithm Given an undirected and disconnected graph G(V, E), print its BFS traversal. python Given an undirected and disconnected graph G(V, E), print its BFS traversal. BFS of graph bfs with queue java BFS of graph gfg bfs dfs java bfs implementation c breath first search cpp breath first search python breath first search in graph examle bfs of graph code graph traversal in c Breadth-first search on a tree in Python bfs graph code in python graph breadth first search using adjacency matrix bfs of graph in cpp Implement Breadth First Search Algorithm Implement a breadth First Search breadth first search bfs in cpp breadth first search algorithm python code breath irst search DFS BFS implementation in c++ implement bfs in java breadth first traversal of a graph breadth first search cpp create Breadth-First Search binary tree python create Breadth-First Search tree python graph breadth first search bfs implementation in c bfs implementation in cpp what is breadth first search java bfs and dfs in cpp breadth first graph traversal a breadth-first search bfs linked list c bfs c linked list bsf in python The Breadth First Traversal algorithm is implemented on given Graph using Queue. One of the possible order for visiting node on given graph: pyhtom bfs alogorithm list breadth search in python node cpp program to implement bfs graph bfs stl recursive Explain Breadth-first search and Depth-first search. Breadth-first search bfs solutions java python depth first search python breadth first search binary tree bfs is used in graph breadth first search and depth first search difference adjacency list bfs c++ breadth first search and depth first search in graphs breadth first search and depth first search bredth first search java bfs in data structure in c bfs function c++ breadth first search arraylist maze how to print in bfs c programming when is breadth-first search is optimal python bfs search bfs queue java c++ code of bfs python code for breadth first search bfs on graph java algorithm breadth first search bfs in c++ using stl Breadth-first search for tree in c tree breadth first search bfs in directed graph example bfs in directed graph breadth first search. implement BFS graph in c++ bfs using set c++ bfs implementation in java Breadth First Search AOJ when breadth first search is optimal all valid bfs in python bfs traversal in graph how to do breadth first traversal breadth first search advantages bfs implementation using c++ bfs linked list in c++ bfs using queue in c++ graph create using list and queue graph creation using breadth first search bfs in java bfs implementation in java example java bfs algorithm graph bfs breadth first traversal of a tree in cpp adjacency matrix breadth first traversal of a tree in cpp apply bfs on the graph given below and show all steps c++ graph implementation bfs java breadth first graph using queue c++ Program to create a graph and use breath First Search implement Graph creation and graph traversal using breadth first search(linked list –queue) programiz bfs dfs porogram of bfsin cpp breath first search algorithm bfs in c++ using queue bread first search python Breadth First Search algorithm can be used to find the graph is connected or not. which ds is used to perform breadth first search of graph breadth search and breadth first search python recursive breadth first search python breadth first search code breadth first binary tree python breadth first search program in c++ breadth first search in c++ using adjacency list breadth first search matrix c++ breathe first search BFS approachable nodes from a given source of a given graph using queue as an intermediate data structure (BFS). java breadth-first traverses bfs code in cpp bfs using c++ breadth first traversal graph dfs and bfs in python BFS traversal in tree cpp (C) Bredth first Search and Depth first bfs in graph bfs traversal of graph bfs java implementation algorithm java bfs Write a program to find approachable nodes from a given source of a given graph using queue as an intermediate data structure (BFS). (Only code) bfs algorithm using geeksforgeeks Program for Breadth First Search (BFS) for graph traversal IN CPP bfs example cpp adjacency list bfs algo cpp adjacency list bfs find out the breardh first tree automatically form the graph Breadth-First Search c++ breadth first search java breath first search of a graph python geeksforgeeks bfs dfs data structure suitable for implementing BFS and bound strategy4 what is bfs in a graph width search algorithm bfs graph BFS directed graph c# breadth first search c++ bredth first search how to do a breadth first search java breadth first search algorithm python maze BFS in c++ breadth first search class python bfs search algorithm in c Which of the following data structures is best to implement BFS Breadth First Search c breath first search (bfs) python code bfs and dfs algorithm in python bfs dfs program in c code for bfs in c breadth first traversal algorithm for tree bfs java graph in python bfs generating a graph for bfs python generating a graph for bfs how to do bfs tree in python bfs algorithm graph list c how to do bfs in python bfs traversal algorithm breathfirst search bfs in python using dictionary write a program to implement breadth first search algorithm using queue bfs c breadth first traversal what is bfs in python Breadth-First Search algorithm python bfs pseudocode in c dfs and bfs in c bfs and dfs of graph in c breadth first search algorithm bfs and dfs algorithm in c c bfs graph breadth first search in c breadth first search c exemple Implement Breadth First Search Graph Traversal technique on a Graph in c Implement Breadth First Search Graph Traversal technique on a Graph. Implement breadth First Search Graph Traversal using c breadth first search in c breadth first search python implementation how to code bfs graph bfs in graph in c Write a program to traverse a graph using breadth-first search (BFS) bfs with graph argument python breath tree search algorithm in python que data structure bfs for search.py breadth-first search python tree bfs in c language using adjacency list breadth first search directed graph c=+ bfs using queue in c++ using adjacency matrix how to do BFS python implement bfs and dfs in c python program for bfs breadth first search tree python Bfs for graphs in c breadth first search in python bfs algos using queues bfs and dfs program in c bfs using queue in java bfs traversal of undirected graph Implement BFS algorithm. Bfs algorithnm in python breadthFirstSearch python bfs c program bfs for graph in python python program for breadth first search traversal for a graph. write a program for breadth first search traversal for a graph python bfs python code with graph output bfs code with graph output python c program for breadth first search traversal of a graph bfs traversal of graph in c breadth first search algorithm implementation python how to do a bfs over a graph python bfs algorithm in python bsf python bfs python breathfirst algorithm to code bfs and dfs in c graph traversal code c graph traversal code rbreadth first search how to implement breadth first search bfs implementation in python implement bfs in python binar first search cide in c cretae agraph and perform bfs from each node in c breadth first search algorithm in c bfs python implementation breadth first search python3 python bfs template breadth first order using adjacency matrix c bfs using adjacency matrix in c Write a program to implement breadth first search algorithm using adjacency matrix in c Write a program to implement breadth first search algorithm using adjacency matrix bfs c implementation breadth for search bfs program in c with explanation bfs traversal in c breadth first traversal python how to implement bfs in python breadth for search python bfs code in c++ bfs program in c write bfs python bfs using adjacency list in c breadth first search python implementation graph search algorithm in c breadth search python Discuss/Illustrate traversing a graph using BFS algorithm bfs using c bfs bt algorithm python Breadth First Search or BFS for a Graph python bfs search python breadth first search pyton Write the program for traversal of graph by using BFS breadth first search gfg bfs graph python how to traverse bfs and dfs python bfs implementation bfs python iterative bfs in c bfs pseudocode python python code for bfs first breadth search code cpp implementing bfs in python how to bfs c++ bfs on graph python bfs cpp graph breadth first search python bfs using queue program in c++ bfs and dfs program in c++ how to impliment bfs in c++ bfs algorithm python code bfs algorithm python bfs example python bfs python simple bfs program in python Breadth-First Search python breadth first python bfs python code bfs source code in java python bfs graph bfs codencode BFS solutions in c++ bfr search graph python python graph bfs breadth first traversal of a graph in python python breadth-first search code bfs python graph breadth first traversal python graph bfs code in c python graphs "breadth first traversal" python graphs breadth first "traversal" python graphs breadth first traversal bfs algorithm implementation in python bfs code python breadth first search code example python breadth first search python program bfs and dfs using python what queue to use for bfs python python code bfs Write a Python program for implementing of bfs bfs code in python breadth first search algorithm python breadth first search algorithm in python graphs breadth firs searching in python implement breadth first search using a queue and while loop bfs python breadth first algorithm python BFS in adjacency matrix python python breadth first search tree iterative bft pythion bfs program in python bfs using stack or queue in c++ Python BFS bfs in python bsf alorithim in python bfs examples bfs using python bfs code breadth first order c++ python breadth first search breadth first search python
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source