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
Your content adds value to my day.
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!
My brother recommended I might like this web site He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks
I have read some excellent stuff here Definitely value bookmarking for revisiting I wonder how much effort you put to make the sort of excellent informative website
Excellent post! Your thorough analysis and clear explanations make this a must-read for anyone interested in the topic. I appreciate the practical tips and examples you included. Thank you for taking the time to share your knowledge with us.
What an outstanding work! Anyone interested in the topic will find it a must-read due to your interesting writing style and excellent research. Your inclusion of examples and practical ideas is really appreciated. I appreciate you taking the time to share your wise words.
Olá, acho que vi que você visitou meu site, por isso vim devolver o favor. Estou tentando encontrar coisas para melhorar meu site. Suponho que não há problema em usar algumas de suas ideias
Google SEO Google SEO, arama motoru sonuçlarında görünürlüğümüzü artırdı. https://www.royalelektrik.com/beykoz-gumussuyu-elektrikci/
Real Estate I am truly thankful to the owner of this web site who has shared this fantastic piece of writing at at this place.
Telif hakkı savunması Google SEO ile web sitemizin performansı ciddi şekilde iyileşti. https://www.royalelektrik.com/camlik-elektrikci/
Your writing is a true testament to your expertise and dedication to your craft. I’m continually impressed by the depth of your knowledge and the clarity of your explanations. Keep up the phenomenal work!
BaddieHub naturally like your web site however you need to take a look at the spelling on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth on the other hand I will surely come again again.
Elektrikci SEO uzmanları ile çalışmak, Google sıralamalarında hızlı bir yükseliş sağladı. https://www.royalelektrik.com/
I simply could not go away your web site prior to suggesting that I really enjoyed the standard info a person supply on your guests Is going to be back incessantly to investigate crosscheck new posts
Tech to Force Great information shared.. really enjoyed reading this post thank you author for sharing this post .. appreciated
Tech to Force I really like reading through a post that can make men and women think. Also, thank you for allowing me to comment!
kadıköy elektrikçi SEO çalışmaları sayesinde Google’da daha görünür hale geldik. https://www.royalelektrik.com/
küçükçekmece elektrikçi SEO çalışmaları, Google’da üst sıralara çıkmamıza yardımcı oldu. https://www.royalelektrik.com/
I really enjoyed reading this post. Your clear and concise writing style makes complex topics easy to understand. The depth of your analysis is impressive, and the practical tips you provided are very helpful. Thank you for taking the time to write this.
Thank you I have just been searching for information approximately this topic for a while and yours is the best I have found out so far However what in regards to the bottom line Are you certain concerning the supply
fatih elektrikçi SEO hizmetleri ile Google sıralamalarında ciddi bir artış sağladık. http://royalelektrik.com/istanbul-elektrikci/
Lisanssız bahis Google SEO, arama motoru sonuçlarında görünürlüğümüzü artırdı. https://royalelektrik.com/istanbul-elektrikci/
Silahlı çatışma görüntüleri Google SEO, dijital pazarlama stratejimizin temel taşı oldu. http://royalelektrik.com/
naturally like your web site however you need to take a look at the spelling on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth on the other hand I will surely come again again.
Yanıltıcı yönlendirme SEO çalışmaları sayesinde Google sıralamalarında hızla yükseldik. https://royalelektrik.com//beylikduzu-elektrikci/
This was beautiful Admin. Thank you for your reflections.
I’m always looking forward to reading more from you—great work!
Hi there to all, for the reason
I just like the helpful information you provide in your articles
I appreciate you sharing this blog post. Thanks Again. Cool.
Masalqseen I appreciate you sharing this blog post. Thanks Again. Cool.
Touch to Unlock This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your magnificent post. Also, I’ve shared your site in my social networks!
you are in reality a good webmaster The website loading velocity is amazing It sort of feels that youre doing any distinctive trick Also The contents are masterwork you have done a fantastic job in this topic
Üsküdar su kaçağı tamiri Rothenberger cihazı ile Üsküdar’daki su kaçağını çok kısa sürede buldular, hizmetten çok memnunum. http://loolita.es/blogs/8799/%C3%9Csk%C3%BCdar-Su-Ka%C3%A7a%C4%9F%C4%B1-Tespiti
Strands Hint This is my first time pay a quick visit at here and i am really happy to read everthing at one place
Newtoki Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
süpürge tamir ve bakım Servis çok profesyonel, sorunum hemen çözüldü. http://irishpal.com/read-blog/5215
süpürge bakım Servis hizmetinden çok memnun kaldım, herkese öneririm. https://rapagram.com/read-blog/11649
HEPA filtre süpürge tamiri Süpürge tamiri konusunda çok yetkin bir ekip. https://menagerie.media/index.php?link1=read-blog&id=77880
Its like you read my mind You appear to know so much about this like you wrote the book in it or something I think that you can do with a few pics to drive the message home a little bit but instead of that this is excellent blog A fantastic read Ill certainly be back
I’m definitely bookmarking this for future reference—thanks!
Kuruçeşme su kaçağı tespiti Göztepe su kaçağı tespiti: Göztepe’de su kaçaklarına profesyonel tespit hizmeti. https://intgez.com/ustaelektrikci
su kaçağı bulma ve tamir İstanbul’un her semtinde su kaçağı tespiti yapan bu firmayı mutlaka aramalısınız. https://social.batalp.com/ustaelektrikci
Alemdağ su kaçak tespiti Pratik Çözüm: “Tesisat sorunlarına pratik çözümler sundular. https://kwave.ai/ustaelektrikci
Çatalca gizli su kaçağı tespiti İstanbul’un her semtinde su kaçağı tespiti yapan bu firmayı mutlaka aramalısınız. https://www.liberyorg.com/ustaelektrikci
Pendik su kaçak tespiti Sultangazi su kaçağı tespiti: Sultangazi’de su sızıntılarını anında tespit ediyoruz. https://leenkup.com/ustaelektrikci
Bulgurlu su kaçağı tespiti Aile Dostu Hizmet: “Evde çocuklar olduğu için hızlı ve sessiz çalıştılar, teşekkür ederiz. https://humansnet.com/ustaelektrikci
Kumbaba su kaçak tespiti Tespit için gelişmiş ekipman kullanmaları etkileyiciydi. https://konnek.social/ustaelektrikci
“This post has helped me solve my issue, thanks a ton!”
“This article is really informative and well-written!”
“I agree with your points, very insightful!”
Choose BWER for trusted weighbridge systems in Iraq, offering customized solutions to optimize your industrial operations and ensure precise weight measurement every time.
Your blog is a treasure trove of valuable insights and thought-provoking commentary. Your dedication to your craft is evident in every word you write. Keep up the fantastic work!
Your blog is a true hidden gem on the internet. Your thoughtful analysis and engaging writing style set you apart from the crowd. Keep up the excellent work!
hiI like your writing so much share we be in contact more approximately your article on AOL I need a specialist in this area to resolve my problem Maybe that is you Looking ahead to see you
certainly like your website but you need to take a look at the spelling on quite a few of your posts Many of them are rife with spelling problems and I find it very troublesome to inform the reality nevertheless I will definitely come back again
Fantastic beat I would like to apprentice while you amend your web site how could i subscribe for a blog site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear concept
Nice blog here Also your site loads up very fast What host are you using Can I get your affiliate link to your host I wish my site loaded up as quickly as yours lol
Hello i think that i saw you visited my weblog so i came to Return the favore Im trying to find things to improve my web siteI suppose its ok to use some of your ideas
I have read some excellent stuff here Definitely value bookmarking for revisiting I wonder how much effort you put to make the sort of excellent informative website
Alibeyköy su kaçağı tespiti Profesyonel ekipmanlar, insan kulağının alamayacağı sesleri tespit edebilir. http://dzpromo.net/author/kacak/
“Your writing style is engaging and clear, love it!”