G-5. Breadth-First Search (BFS) | C++ and Java | Traversal Technique in Graphs

Поділитися
Вставка
  • Опубліковано 25 лис 2024

КОМЕНТАРІ •

  • @takeUforward
    @takeUforward  2 роки тому +102

    Let's continue the habit of commenting “understood” if you got the entire video.
    Do follow me on Instagram: striver_79

  • @UECSoumyaRay
    @UECSoumyaRay Рік тому +403

    I can proudly say that this summer I watched more tUf lectures than Netflix episodes.

    • @aniket6858
      @aniket6858 Рік тому +26

      Because your placement season is here

    • @Moch117
      @Moch117 Рік тому +6

      @@aniket6858 What is placement? Is this india

    • @joseph2073
      @joseph2073 Рік тому +16

      @@Moch117 no, its pakistan.

    • @congdatt
      @congdatt 6 місяців тому

      what is the result ?

    • @montynathan3318
      @montynathan3318 5 місяців тому +5

      Yoh Netfilix ke hovey?😶‍🌫️

  • @YeaOhYeahh
    @YeaOhYeahh 2 роки тому +223

    If u r confused about time complexity part, then see the following dry run of the while loop of the qs. he has solved..
    This is how nodes are connected(assuming undirected graph) :
    0 -> 1 ,2, 3
    1 -> 0
    2 -> 0, 4
    3 -> 0
    4 -> 2
    So, total no. of edges = E = 4
    For first while loop ,
    node = 0, edges = 3
    Now, before going to the for loop part, u see a constant time operation O(1) --> q.pop( )
    This step will be executed every time we enter into while loop.
    So, for first while loop how many times for loop will execute ??
    It will be equal to the no. of edges , here it will be 3.
    Therefore, total = ( 1 + 3 )
    Similarly for all other nodes, this is how it will look :
    ( 1 + 3 ) + ( 1 + 1 ) + ( 1 + 2 ) + ( 1 + 1 ) + ( 1 + 1 )
    = 13
    = O ( V + 2 * E )
    = O ( 5 + 2 * 4 )

    • @sumerrawat6947
      @sumerrawat6947 2 роки тому +6

      Very well explained !

    • @Saurav_Kumar514
      @Saurav_Kumar514 2 роки тому +3

      Awesome 👌👌

    • @mypowerlevelisover9000
      @mypowerlevelisover9000 Рік тому +1

      Thank you

    • @YeaOhYeahh
      @YeaOhYeahh Рік тому +1

      @@mypowerlevelisover9000 🙂

    • @shaikhfaisal2423
      @shaikhfaisal2423 Рік тому +7

      but at the worst case it will be O(n^2) right? since a complete graph have all the vertex with (n-1) edges. which will lead [(1+(n-1))=n] at each while and for loop. since after n times it will become n square. Please confirm this. BTW thanks for the explaination

  • @HARSHKAJALKHANEIIIIIIII
    @HARSHKAJALKHANEIIIIIIII Місяць тому +3

    THOSE WHO ARE WORDERING WHY IT IS O(N) + O(2E) NOT O(N*2E)
    For each node, the while loop runs multiple times based on the number of edges connected to that node. Here's how it works:
    In the first iteration, the loop runs for e1 edges, plus one extra operation for pushing and popping the node.
    In the second iteration, it runs for e2 edges, plus one extra operation for pushing and popping, and so on.
    Thus, the total time complexity is the sum of all iterations:
    (e1 + e2 + ... + en) + (1 + 1 + ... n times).
    The sum of all the edges connected to each node is equal to the total number of edges, which is 2E (since each edge is counted twice in an undirected graph). Adding the n push/pop operations gives the final complexity:
    O(V + 2E) because e1 + e2 + ... + en = 2E.
    So, the overall complexity is O(V + 2E), which simplifies to O(V + E).

  • @gourabbhattacharjee2128
    @gourabbhattacharjee2128 Рік тому +9

    Just some simple words! No one can beat your DSA teaching style!!

  • @chitrankusarkar7278
    @chitrankusarkar7278 Рік тому +57

    17:04 i was still wondering where the heck vis[n] came from. edited like a pro

  • @creativearts6406
    @creativearts6406 7 місяців тому +3

    I like the way you explain time and space complexities, which actually helps me to analyze my code complexities. Thanks for the explanation.

  • @nkgautam6161
    @nkgautam6161 2 роки тому +13

    you are great striver.
    Explain such a complex topic in very easy manner.
    Your method of teaching is unique, a unique lecture by a unique teacher🙏🙏🙏

  • @somz21ad
    @somz21ad 2 роки тому +10

    Hey Striver! Thank you for creating outstanding content and helping people interested in coding problems worldwide! Please don’t stress yourself out, take a break after this one. It’s not easy to work full time and dedicate time for this.

  • @arthurdark3945
    @arthurdark3945 2 роки тому +96

    Are you going to teach leetcode questions just like you did in DP series? It would be very helpful if you can teach commonly asked good questions covering different graph patterns and not just the basic ones.

    • @takeUforward
      @takeUforward  2 роки тому +135

      Yups, this one is going to be 50+ videos.

    • @pranavsharma7479
      @pranavsharma7479 2 роки тому +14

      @@takeUforward bro try to cover as max you can till 15 aug, thnks for helping

  • @asadeducation9513
    @asadeducation9513 8 місяців тому +2

    understood..awesome..most of the youtuber's don't explain a topic in depth... great video

  • @supriyamanna715
    @supriyamanna715 Рік тому +13

    coded on my own! Got an error, resolved the issue, all TC passed! Note taken

    • @futurev14
      @futurev14 Рік тому

      Toh tujhe kya lg rha bada jhanda gaad diya tune saale itne chappal maruga

  • @priyadarsinipaikaray4998
    @priyadarsinipaikaray4998 Рік тому +3

    You are amazing 🤩
    Guru wo hota h jo muskil si cheez ko v Asan karde tushi great ho ji striver ❤

  • @YCCMdigo
    @YCCMdigo 2 місяці тому

    Thank you man from the bottom of my heart for this video. You're one of the greatest instructors i've ever seen

  • @multiverseofcomputerscience
    @multiverseofcomputerscience 2 роки тому +2

    after seeing your post on LinkedIn that you are launching graph series 2.0 i used to see your UA-cam playlist daily now I am very happy thank you very much 💗

  • @anuraggoswami3534
    @anuraggoswami3534 2 роки тому

    57 +videos trurly 🇮🇳 biggest graph series Ironically GOAT 🐐 is teaching GRAPH 🤩

  • @siddharthpatil3046
    @siddharthpatil3046 6 місяців тому +1

    Time complexity of BFS may be different depending upon representation of graph.
    Adjacency List: O(V+E)
    Adjacency Matrix: O(V^2)
    where V=no of vertex and E = no of edges

  • @tharaniarumugam-zb9il
    @tharaniarumugam-zb9il 4 місяці тому

    Your videos never fail to save us anytime :) Undhan rasigaiyee naaum unaken puriyavillai...

  • @yashrawat5158
    @yashrawat5158 Рік тому

    those who are doing on Codestudio we first have to create adjlist first
    so here the easy solution to it using set
    #include
    void prepareList(unordered_map &adjlist,vector &edges){
    for(int i=0;i

  • @prakharjain6611
    @prakharjain6611 11 місяців тому +4

    17:02 the code he wrote has errors , 17:06 the errors are gone .

  • @raghvendrakhatri5848
    @raghvendrakhatri5848 2 роки тому +4

    Understood each and every word♥. Kudos to your hard work and dedication, you are the motivation behind a lot of people. Your hardwork inspires a lot of people to work hard.
    Thankyou for providing such a beautiful graph series keep posting such content ♥, we all need this.

  • @test-nature
    @test-nature 3 місяці тому

    I was happy to say that I will do and understand first graph problem.🎉

  • @shreyyyc
    @shreyyyc Рік тому +1

    Thanks a lot stiver for putting all these playlists out. i can't imagine getting a job if you were not on youtube. i have a little doubt that in "bfsOfGraph" function the syntax of adj[ ] should be this "Vector> adj [ ]" but it is "vector adj[ ]" instead and this is a 1D vector not a vector of vector.

    • @iitbhuvictim
      @iitbhuvictim Рік тому +1

      Here you're creating an array of vector.... basically number of vector is fixed....that is the way to create array of vectors

    • @lakshsinghania
      @lakshsinghania Рік тому

      there is a similar comment in the video number G-2 check that out

    • @ayushmishra9758
      @ayushmishra9758 Рік тому

      Hence, vectoradj[n]
      n is no of vertices.(0 based) . adj creates an array where each adj[i] is a vector itself. Array of VECTORS.

    • @prachi1112
      @prachi1112 Рік тому

      Same doubt. if we're storing an array at each index of the vector, shouldn't it be vector adj instead of vectoradj??

    • @ShivamTh405
      @ShivamTh405 Рік тому +6

      @@prachi1112 We are storing vector in array index, i.e array of vectors. Every node of array denotes an array . Eg -> if we write int arr[] , here data type is int , so it is array of integers, but if we write vector arr[] , here data type is vector , so it is array of vector

  • @MischievousSoul
    @MischievousSoul Рік тому +1

    There was some sound glitch for 30 sec.. Was weird but
    Loved the way you teach and i am here after conpleting your trees playliat... ❤

  • @ancycoding
    @ancycoding Рік тому

    BEST DSA TEACHER FOR ME

  • @simmi641
    @simmi641 Рік тому +1

    Thank you so much stiver. Happy Teachers dayy

  • @udaypratapsingh8923
    @udaypratapsingh8923 2 роки тому +1

    here we go !

  • @addictedtocricket8827
    @addictedtocricket8827 Рік тому

    how can someone be so perfect in explianing concept

  • @kulkarnisoham
    @kulkarnisoham Рік тому +1

    Awesome Space & Time Analysis 🔥🔥🔥🔥🔥🔥🔥🔥

  • @hashcodez757
    @hashcodez757 3 місяці тому

    "UNDERSTOOD BHAIYA!!"

  • @atharvameher5880
    @atharvameher5880 Рік тому +1

    My favourite algorithm so far, Breast First Search

  • @ajoydev8876
    @ajoydev8876 11 місяців тому

    complexity : O(V + 2E)
    let say,
    adjacency list :
    1 - {2,3}
    2 - {1,4,5,6}
    3 - {1,7,8}
    4 - {2}
    5 - {2}
    6 - {2}
    7 - {3}
    8 - {3}
    for node 1, way = 2
    for node 2, way = 4
    for node 3, way = 3
    for node,4 way = 1
    for node 5, way = 1
    for node 6, way = 1
    for node 7, way = 1
    for node 8 , way = 1
    total way = 2 + 4 + 3 + 1 + 1 + 1 + 1 +1 = 14
    Node = 8
    total = 14 + 8 = 22
    where, O(V + 2E)
    V = 8
    E = 7
    total = 8 + 2*7 = 22
    O(V + 2E) = 22

  • @rameshbabuy9254
    @rameshbabuy9254 Рік тому +3

    please also explain space and time complexities

  • @Sillysmiles76
    @Sillysmiles76 Рік тому

    Understood, Happy Learning🤗

  • @GeneralistDev
    @GeneralistDev Рік тому +4

    9:39 ASMR moments

  • @oqant0424
    @oqant0424 2 роки тому +2

    5/56 done(3.12.22)

  • @alt-f4gaming222
    @alt-f4gaming222 Рік тому

    congrats bhaiya for 300k
    ek din apan sath me 1m jayenge

  • @satishsingh8297
    @satishsingh8297 2 роки тому +1

    Thankyou striver bhaiya! ❤️

  • @syedfaheem1185
    @syedfaheem1185 Місяць тому +3

    I am having a question regarding the TC. How can it be O(N+2E). Since, the outer loop runs as long as the queue isn't empty, which means it will run exactly N times and for each vertex or node, we check if the neighbours are visited and if not, we add them to the queue. Now, at each node, we're checking whether it's neighbours are visited or jot which is itself an O(1) operation. So, for N nodes, we are performing operations equal to the degree of a node. How can the TC not be O(n*avg. degree).

  • @aniketshukla2426
    @aniketshukla2426 2 роки тому +3

    What about Directed Graphs, It applies for them too?
    I think yes, because the adjacency list will only have those edges so we only traverse those edges

  • @Maunil2k
    @Maunil2k 7 місяців тому

    Nice and crystal clear explanation !!

  • @farazjawaid2982
    @farazjawaid2982 Рік тому +1

    a well explained and organised lecture !!!

  • @stith_pragya
    @stith_pragya 11 місяців тому

    Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @cinime
    @cinime 2 роки тому +1

    Understood! Awesome explanation as always, thank you so much!

  • @DevanshuAugusty
    @DevanshuAugusty Рік тому +6

    17:03 i see what you did there 🤣🤣

    • @alina8023
      @alina8023 11 місяців тому +1

      no one commented on this :(

  • @AryanVerma-y3m
    @AryanVerma-y3m 4 місяці тому

    you are the best stiver

  • @aniketshukla2426
    @aniketshukla2426 2 роки тому +7

    I'm confused on the Time complexity,
    If we know the while loop runs N times and the size of the adjacency list is 2E, It is alright to add them to get the time complexity?
    like, the while loop runs N times and the for loop overall runs 2E times..??

  • @tanaysingh5348
    @tanaysingh5348 2 роки тому

    very well explained with all the minute details

  • @ramanpareek5218
    @ramanpareek5218 4 місяці тому

    Liked the video, notes taken, understood

  • @atharvamore342
    @atharvamore342 Рік тому +2

    14:30 program starts

  • @its_kundan
    @its_kundan 5 місяців тому +2

    what if the graph have different components?
    the solution seems to solve the connected components only.

  • @aditya_raj7827
    @aditya_raj7827 10 місяців тому

    You are amazing striver ❣️

  • @raiusamaakram
    @raiusamaakram 2 роки тому

    brilliantly explain thanks sir and neeed complete playlist of DSA from you for cracking google like companies

  • @akshaikumar7966
    @akshaikumar7966 Рік тому

    i loved it sir , what a beautiful explanation

  • @paullater6230
    @paullater6230 6 місяців тому

    understood!! Explained beautifully!!

  • @dhananjayg8332
    @dhananjayg8332 2 роки тому

    crystal clear.. excellent explanantion

  • @shashankdesai8650
    @shashankdesai8650 Рік тому

    Ohoo masthhh bhaiyaaaa Woohoo

  • @p38_amankuldeep75
    @p38_amankuldeep75 2 роки тому

    great content loving this after completing dp series💙💛💙

  • @likhitbhogadi
    @likhitbhogadi 7 місяців тому

    hats off to ur hard work.

  • @karthik-varma-1579
    @karthik-varma-1579 18 днів тому +3

    Telugu people attendance❤

  • @sripriyapotnuru5839
    @sripriyapotnuru5839 2 роки тому

    Thank you, Striver

  • @RanjeetKumar-dr5ds
    @RanjeetKumar-dr5ds 2 роки тому +1

    understood

  • @UECAshutoshKumar
    @UECAshutoshKumar Рік тому +1

    Thank you sir

  • @BharatKumar-rc8vn
    @BharatKumar-rc8vn 4 місяці тому

    made it simple to understand

  • @ExpoDev_Dash
    @ExpoDev_Dash 11 місяців тому

    00:01 Breadth-First Search (BFS) is a traversal technique in graphs.
    02:16 Breadth-first search (BFS) traversal of the graph
    04:25 Breadth-First Search (BFS) is a traversal technique in graphs.
    06:37 Breadth-First Search (BFS) is a traversal technique in graphs.
    08:54 Performing BFS traversal on a graph using adjacency list representation
    11:35 BFS traversal of graph
    14:04 Implementing Breadth-First Search (BFS) in C++ and Java
    16:01 Breadth-First Search (BFS) is a traversal technique used in graphs.
    18:04 BFS algorithm runs on all the neighbors of each node
    Crafted by Merlin AI.

  • @morganyu3391
    @morganyu3391 2 роки тому

    Understood bhaiya!

  • @paulangelp7099
    @paulangelp7099 9 місяців тому

    Fantastic 🎉 Understood

  • @ayat_middya
    @ayat_middya 2 роки тому

    Wonderful bhaiya.....

  • @subhamoybera6456
    @subhamoybera6456 Рік тому

    Great explanation

  • @samuelfrank1369
    @samuelfrank1369 Рік тому

    Understood. Thanks a lot.

  • @codeman3828
    @codeman3828 6 місяців тому

    Great series

  • @ayushagrawal6700
    @ayushagrawal6700 Рік тому +2

    I think bool data type will be better than int data type for visited array because bool data type takes 1 byte whereas int data type takes 4 bytes.
    And If I am wrong pls correct me :)

    • @infinityzero2321
      @infinityzero2321 Рік тому

      ya no issue ... just taking int as it would help with weighted graphs as well and generalize the approach

  • @hopelessboys3004
    @hopelessboys3004 6 місяців тому

    love you from bangladesh

  • @kartikshukla5018
    @kartikshukla5018 Рік тому

    Thanks sir .... best solutions

  • @mriduljain6809
    @mriduljain6809 Рік тому

    Understood Bhaiya

  • @abhichi
    @abhichi 2 роки тому

    Understood..next please ✌🏻

  • @rajsekhardutta8891
    @rajsekhardutta8891 2 роки тому

    What an amazing explanation! Understood! 🤩❤‍🔥

  • @ashish2736
    @ashish2736 Рік тому +4

    Hi @TakeUforward, I had a doubt, when the for loop is inside the while loop, shouldn't we multiply the time complexities instead of adding them?

    • @IITians
      @IITians Рік тому +11

      understand with the following explanation (just copy-pasted)
      This is how nodes are connected(assuming undirected graph) :
      0 -> 1 ,2, 3
      1 -> 0
      2 -> 0, 4
      3 -> 0
      4 -> 2
      So, total no. of edges = E = 4
      For first while loop ,
      node = 0, edges = 3
      Now, before going to the for loop part, u see a constant time operation O(1) --> q.pop( )
      This step will be executed every time we enter into while loop.
      So, for first while loop how many times for loop will execute ??
      It will be equal to the no. of edges , here it will be 3.
      Therefore, total = ( 1 + 3 )
      Similarly for all other nodes, this is how it will look :
      ( 1 + 3 ) + ( 1 + 1 ) + ( 1 + 2 ) + ( 1 + 1 ) + ( 1 + 1 )
      = 13
      = O ( V + 2 * E )
      = O ( 5 + 2 * 4 )

    • @vip-qg1zl
      @vip-qg1zl 9 місяців тому

      ​@@IITiansgreat

  • @rishabhagarwal8049
    @rishabhagarwal8049 2 роки тому

    Understood Sir, Thank you very much

  • @yashpadiyar4952
    @yashpadiyar4952 2 роки тому +1

    Thankuu sooo muchhh broooo🤗🤗🤗❤❤❤❤❤

  • @Highlights_Point
    @Highlights_Point 2 роки тому +1

    Thanks Bhaiya

  • @ankitz007
    @ankitz007 2 роки тому

    Understood, Sire!

  • @udayrajvadeghar8555
    @udayrajvadeghar8555 6 місяців тому

    UNDERSTOOD!

  • @vakhariyajay2224
    @vakhariyajay2224 Рік тому

    Thank you very much. You are a genius.

  • @vikasbagri1225
    @vikasbagri1225 2 роки тому

    understood very well...

  • @abdalla4425
    @abdalla4425 10 місяців тому

    Interesting that you have to set 0 as visited missed that when I first tried it!

  • @sagaravhad5198
    @sagaravhad5198 Рік тому

    Thank you so much.

  • @umeshkaushik710
    @umeshkaushik710 2 роки тому

    Great work. Thanks for doing this.

  • @gunahawk6893
    @gunahawk6893 Рік тому

    Woah nice explanation

  • @varunkumar-vs5wc
    @varunkumar-vs5wc Рік тому

    all clear thank u bro

  • @doingdifferent7714
    @doingdifferent7714 2 роки тому +10

    Wont Time Complexity be O(n*2E)?? Since for each node n we are traversing 2E

    • @takeUforward
      @takeUforward  2 роки тому +17

      But once you have travelled for all nodes, all are visited, you won’t again traverse na. Overall you will travel everyone once only

    • @CuriousAnonDev
      @CuriousAnonDev 2 роки тому +25

      nooo!!!
      you don't know what E is!!
      E is total no of edges of whole graph in V + E
      in your n*E, E is no of neighbours of a particular node!!!
      see...
      for every node(while loop) you are running "for" loop for number of times==number of its neighbours
      so in that case you can say n*e
      but the thing is this -> for every node number of neighbours are different hence we don''t write complexity like you have written
      while loop n times run karega aur andar wala for loop jo hai, woh in total, sab while loop ka milake, E(total edges in whole graph) times run karega
      isliye toh add kiya N aur E ko
      ab clear ho jana chahiye
      me bhi atka tha ispe 3-4 dinse
      same concept dijkstra, prims me bhi apply hoga so make sure you understand it!

    • @dhananjayvaish3276
      @dhananjayvaish3276 2 роки тому +1

      @@CuriousAnonDev thanks for indepth explaination !

    • @Lullurluli
      @Lullurluli Рік тому

      @@CuriousAnonDev naam dekh kar mai bhi atak gaya

  • @aasifali9139
    @aasifali9139 Рік тому

    thx striver. Understood.

  • @VivekSharma-eh2tv
    @VivekSharma-eh2tv 5 місяців тому +1

    striver you didn't explained why it would work for a directed graph

  • @adebisisheriff159
    @adebisisheriff159 10 місяців тому

    thanks Raj

  • @adityaroychowdhury3709
    @adityaroychowdhury3709 2 роки тому

    understood
    thankyou very much

  • @tanvirhasanmonir1627
    @tanvirhasanmonir1627 Рік тому

    Thank you, understood!

  • @nandini2783
    @nandini2783 Рік тому

    Thankyou striver!

  • @farheenkhan3248
    @farheenkhan3248 Рік тому

    just thank you 🙏

  • @kritagyaprasad7230
    @kritagyaprasad7230 2 роки тому

    Great Content

  • @mahaprasadm9770
    @mahaprasadm9770 2 роки тому

    brilliant explanation!