Graph BFS Java Example

We are going to traverse the below graph using BFS Traversal starts from node 0.

0 -> 3 | 0 -> 2 | 2 -> 1 =========> 0, 3, 2, 1

package com.ngdeveloper.algo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BFS {

    public static void main(String[] args) {
        Graph graph = new Graph(4);
        graph.addEdge(0, 3);
        graph.addEdge(0, 2);
        graph.addEdge(2, 1);
        graph.bfs(0);
    }

    private static class Graph{
        private int vertices;
        private List<List<Integer>> adjacencyList;

        public Graph(int vertices){
            this.vertices = vertices;
            this.adjacencyList = new ArrayList<>(vertices);
            for(int i=0;i<vertices;i++){
                this.adjacencyList.add(new ArrayList<>());
            }
        }

        public void addEdge(int source, int destination) {
            this.adjacencyList.get(source).add(destination);
            this.adjacencyList.get(destination).add(source);
        }

        public void bfs(int start){
            boolean[] visited = new boolean[vertices];
            visited[start] = true;
            System.out.println("Traversed: "+start);
            Queue<Integer> queue = new LinkedList<>();
            queue.add(start);
            while(!queue.isEmpty()) {
                int node = queue.poll();
                List<Integer> neighbors = adjacencyList.get(node);
                for(Integer neighbor: neighbors){
                    if(!visited[neighbor]) {
                        visited[neighbor] = true;
                        queue.add(neighbor);
                        System.out.println("Traversal: "+neighbor);
                    }
                }
            }
        }
    }
}
Traversed: 0
Traversal: 3
Traversal: 2
Traversal: 1

20 comments

  • Your content adds value to my day.

  • Serena2934

    The Beatles – легендарная британская рок-группа, сформированная в 1960 году в Ливерпуле. Их музыка стала символом эпохи и оказала огромное влияние на мировую культуру. Среди их лучших песен: “Hey Jude”, “Let It Be”, “Yesterday”, “Come Together”, “Here Comes the Sun”, “A Day in the Life”, “Something”, “Eleanor Rigby” и многие другие. Их творчество отличается мелодичностью, глубиной текстов и экспериментами в звуке, что сделало их одной из самых влиятельных групп в истории музыки. Музыка 2024 года слушать онлайн и скачать бесплатно mp3.

  • This asset is phenomenal. The wonderful information exhibits the maker’s earnestness. I’m stunned and anticipate more such mind blowing posts.

  • This asset is phenomenal. The wonderful information exhibits the proprietor’s earnestness. I’m stunned and anticipate more such mind blowing entries.

  • This is an amazing page. The outstanding information reveals the owner’s accountability. I’m in awe and eagerly await more amazing postings like this one.

  • It seems like you’re repeating a set of comments that you might have come across on various websites or social media platforms. These comments typically include praise for the content, requests for improvement, and expressions of gratitude. Is there anything specific you’d like to discuss or inquire about regarding these comments? Feel free to let me know how I can assist you further!

  • Thank you for reaching out! If you have any specific questions or topics in mind, please feel free to share them, and I’ll do my best to assist you. Whether you’re curious about a particular technology, scientific concept, literary work, or anything else, I’m here to provide information, advice, or engage in a discussion. Don’t hesitate to let me know how I can help you further!

  • I do not even know how I ended up here but I thought this post was great I dont know who you are but definitely youre going to a famous blogger if you arent already Cheers.

  • You have a way of making each of your readers feel seen and heard That’s a special quality that not all bloggers possess Thank you for creating a safe space for us

  • Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do it Your writing style has been amazed me Thank you very nice article.

  • I truly enjoyed what you’ve achieved here. The design is stylish, your written content fashionable, yet you appear to have acquired some apprehension regarding what you intend to present going forward. Undoubtedly, I’ll return more frequently, similar to I have almost constantly, in the event you sustain this ascent.

  • I truly savored what you’ve accomplished here. The sketch is elegant, your authored material trendy, however, you seem to have developed some trepidation about what you aim to offer next. Certainly, I shall revisit more regularly, just as I have been doing nearly all the time, in case you uphold this ascension.

  • I truly enjoyed what you’ve achieved here. The design is stylish, your written content fashionable, yet you appear to have acquired some apprehension regarding what you intend to present going forward. Undoubtedly, I’ll return more frequently, similar to I have almost constantly, in the event you sustain this ascent.

  • I truly relished the effort you’ve invested here. The design is tasteful, your authored material fashionable, however, you seem to have acquired some unease about what you intend to present henceforth. Undoubtedly, I’ll revisit more regularly, similar to I have nearly all the time, in the event you sustain this rise.

  • I truly admired the work you’ve put in here. The design is refined, your authored material stylish, however, you seem to have acquired some trepidation about what you intend to present next. Undoubtedly, I’ll revisit more regularly, similar to I have nearly all the time, in the event you sustain this rise.

  • I truly enjoyed what you’ve achieved here. The design is stylish, your written content fashionable, yet you appear to have acquired some apprehension regarding what you intend to present going forward. Undoubtedly, I’ll return more frequently, similar to I have almost constantly, in the event you sustain this ascent.

  • The breadth of knowledge compiled on this website is astounding. Every article is a well-crafted masterpiece brimming with insights. I’m grateful to have discovered such a rich educational resource. You’ve gained a lifelong fan!

  • Your content is consistently exceptional.

  • Thank you for your response! I’m grateful for your willingness to engage in discussions. If there’s anything specific you’d like to explore or if you have any questions, please feel free to share them. Whether it’s about emerging trends in technology, recent breakthroughs in science, intriguing literary analyses, or any other topic, I’m here to assist you. Just let me know how I can be of help, and I’ll do my best to provide valuable insights and information!

  • Your blog has quickly become my go-to source for reliable information and thought-provoking commentary. I’m constantly recommending it to friends and colleagues. Keep up the excellent work!

Leave a Reply