bfs python

graph = {
  '5' : ['3','7'],
  '3' : ['2', '4'],
  '7' : ['8'],
  '2' : [],
  '4' : ['8'],
  '8' : []
}

visited = [] # List for visited nodes.
queue = []     #Initialize a queue

def bfs(visited, graph, node): #function for BFS
  visited.append(node)
  queue.append(node)

  while queue:          # Creating loop to visit each node
    m = queue.pop(0) 
    print (m, end = " ") 

    for neighbour in graph[m]:
      if neighbour not in visited:
        visited.append(neighbour)
        queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')    # function calling

3.63
8

                                    // 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;
}

3.63 (8 Votes)
0
0
0

                                    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

0
0
4.13
8

                                    # 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.13 (8 Votes)
0
3.6
5
Natia 80 points

                                    graph = {
  'A' : ['B','C'],
  'B' : ['D', 'E'],
  'C' : ['F'],
  'D' : [],
  'E' : ['F'],
  'F' : []
}

visited = [] # List to keep track of visited nodes.
queue = []     #Initialize a queue

def bfs(visited, graph, node):
  visited.append(node)
  queue.append(node)

  while queue:
    s = queue.pop(0) 
    print (s, end = " ") 

    for neighbour in graph[s]:
      if neighbour not in visited:
        visited.append(neighbour)
        queue.append(neighbour)

# Driver Code
bfs(visited, graph, 'A')

3.6 (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
bfs graph traversal in data structure 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 python code for bfs algorithm bfs in python inbuilt bfs algorithm graph in c bfs traversal algorithm in c code for bfs in python breadth search algorithm python bfs python example breadth first search python library c program Implementation of Graph traversal - Depth First Search write a program to implement breadth first search using python stack python using breadth first search simple graph bfs traversal in 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 breadth first tree traversal python breadth first search python tree traversing graph by bfs python bfs and dfs breadth first search using python implementing breadth first search in python breadth first search bfs program in python graph traversal bfs question 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 graph representation and breadth first traversal program in c bfs on python python breadth first traversal bfs traversal gfg code of bfs in python BFS search for graph traversal algorithm breadth first search tree traversal python python breadth-first search breadth first search source code in python bfs code in python as a function bfs level order traversal graph graph to bfs traversal breadth first traversal of a graph in c bfs traversal of tree ca bfs traversal of graph gfg how to find all bfs traversals of a graph implementing a breadth first search in python BFT python bfs traversal and dfs traversal graph graph bfs traversal how to traverse a graph using bfs bfs traversal code c++ bfs traversal code Write a C program to traverse the below graph using Depth first traversal and Breadth first traversal breath first search in ython Implement BFS algorithm using python python bfs code breadth first search using class python bfs python program Breadth-first Search python code breadth first search path python breadth first implementation in python Breadth First Search algorithm on graph python implementation Breadth First Search algorithm python implementation bfs graph traversal example bfs graph traversal bfs python explained bfs traversal of grapht bfs python algorithm bfs and dfs in c++ bfs and dfs bfs traversal of a graph python bfs example 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 bfs python tre how to use BFS in python two way breadth first search python how to implement breadth first search in python bfs in python 3 python breadth first search breadfirst search breadth first search pythn breadth first search python code breadth first search implementation python what is breadth first search python tree breadth first search python 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 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 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 code gfg breadth first search explained bfs of following graph starting from vertex A bfs of following graph vertex A Breadth-First Graph Search 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 algorithm c++ 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 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 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 breadth first search and depth first search 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 python code for breadth first search bfs on graph java algorithm breadth first search 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 implementation in java Breadth First Search AOJ when breadth first search is optimal all valid bfs in python how to do breadth first traversal breadth first search advantages bfs linked list in c++ bfs using queue in c++ graph create using list and queue bfs in java 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 implement Graph creation and graph traversal using breadth first search(linked list –queue) programiz bfs dfs 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 code in cpp bfs using c++ breadth first traversal graph dfs and bfs in python BFS traversal in tree cpp bfs in graph bfs traversal of graph bfs example cpp adjacency list bfs data structure suitable for implementing BFS and bound strategy4 what is bfs in a graph width search algorithm bfs graph BFS directed graph c# bredth first search breadth first search algorithm python maze 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