G-2. Graph Representation in C++ | Two Ways to Represent

Поділитися
Вставка
  • Опубліковано 4 сер 2022
  • Notes Link: takeuforward.org/graph/graph-...
    DP Series: • Striver's Dynamic Prog...
    SDE Sheet: takeuforward.org/interviews/s...
    Check out our Website for curated resources:
    Our Second Channel: / @striver_79
    In case you are thinking to buy courses, please check below:
    Code "takeuforward" for 15% off at GFG: practice.geeksforgeeks.org/co...
    Code "takeuforward" for 20% off on sys-design: get.interviewready.io?_aff=takeuforward
    Crypto, I use the Wazirx app: wazirx.com/invite/xexnpc4u
    Take 750 rs free Amazon Stock from me: indmoney.onelink.me/RmHC/idje...
    Earn 100 rs by making a Grow Account for investing: app.groww.in/v3cO/8hu879t0
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    ---------------------------------------------------------------------------------------------------------------------------

КОМЕНТАРІ • 287

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

    Lets continue the habit of commenting “understood” if you got the entire video.
    Do follow me at Instagram: striver_79

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

      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.

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

      @take U forward the complexity at 6:44 if it is 0 indexed should be n*n or n*m ? and the complexity at 7:17 should be O(m) I guess . Please let me know

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

      @@nisha_k22 You are right

    • @BhavyaJain-qz8jg
      @BhavyaJain-qz8jg 7 місяців тому

      understood

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

    I just wanted to say that u are pure gem for us and keep going the way you are going. Lots of thanks 🙏🙏

  • @raregem7995
    @raregem7995 14 днів тому +4

    In the adj matrix code at 06:37 there will be adj[n+1][n+1], not adj[n+1][m+1]. We all understood this from your explanation. Thank you for such great playlists.💛

  • @user-ki5hf5sq4t
    @user-ki5hf5sq4t Місяць тому +12

    2D Vector (vector)
    Dynamic: Both dimensions (rows and columns) can be resized dynamically.
    Usage: Suitable when the number of vertices is not known at compile time or can change.
    Syntax: vector adjList(vertices);
    Array of Vectors (vector adj[])
    Fixed Outer Dimension: The number of rows (vertices) is fixed at compile time.
    Dynamic Inner Dimension: The number of columns (edges per vertex) can change dynamically.
    Usage: Suitable when the number of vertices is known and fixed at compile time.
    Syntax: vector adj[n+1];

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

    the best explanation of graphs till now... thanks striver

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

    For storing in adjacency matrix, it will be int adj[n][n] if nodes are numbered from 0 to n-1 and adj[n+1][n+1] if nodes are numbered from 1 to n

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

      yes... even I was thinking the same during the lecture

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

      why n+1

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

      @@johnxina7496 Because of 1-based indexing, if you'll take it n then n-th node will not get added.

    • @user-oy7ky9zk9l
      @user-oy7ky9zk9l 2 місяці тому +2

      he also did a mistake of taking n+1 * m+1 it should be n+1 * n+1

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

    from past 3-4 months I was running away from the graph but I got some hope after watching this video. 😍

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

    Understood! Great explanation as always, thank you very much!!

  • @mayank_rampuriya
    @mayank_rampuriya Рік тому +18

    It would be better if we use *map m* rather than *vector v[n+1]*

    • @Sameer-wx2pd
      @Sameer-wx2pd 3 місяці тому

      Why bro

    • @divyam-hx3ie
      @divyam-hx3ie Місяць тому +1

      @@Sameer-wx2pd because we have a vector corresponding to single integer, example 1 is connected to 2 and 3 so, key is 1 and have value in the form of vector containing 2 and 3

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

    Some compilers like Visual C++ don't support variable length arrays. So you will get compilation error for using non-constant n and m as array indexes. In that case you can use vector as follows:
    //Adjacency Matrix representation
    ===========================
    #include
    #include
    using namespace std;
    int main() {
    int nodes, edges, u, v;
    cin >> nodes >> edges;
    // declare the Adjacency matrix
    vector adj;
    adj.resize(nodes + 1);
    // take edges as input
    for (int i = 0; i < edges; i++) {
    cin >> u >> v;
    adj[u][v] = 1;
    adj[v][u] = 1;
    }
    return 0;
    }
    //Adjacency List representation
    =========================
    #include
    #include
    using namespace std;
    int main() {
    int nodes, edges, u, v;
    cin >> nodes >> edges;
    // declare the Adjacency list
    vector adj;
    adj.resize(nodes + 1);
    // take edges as input
    for (int i = 0; i < edges; ++i)
    {
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
    }
    return 0;
    }

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

      At last, I was racking my head trying to understand how using vector we were able to represent a 2D matrix. Thanks, bro

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

      @@srianshumahadas7178 Welcome!
      int matrix[M][N] can be represented as vector matrix(M, vector(N)) .

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

    The adjacency matrix is better if we are concerned about time complexity as it finds edge b/w nodes in O(1). Yes, in the case of something like a sparse graph, we should prefer an adjacency list otherwise we would waste too much space.

  • @tasneemayham974
    @tasneemayham974 7 місяців тому +9

    I finished the ENTIRE dp series. THE BESSTTT. Now I am here for graphss!!
    Thank youu sooo much Striver!!!

    • @harshitrautela6585
      @harshitrautela6585 27 днів тому +1

      do you suggest completing graph or dp series before?

    • @tasneemayham974
      @tasneemayham974 26 днів тому +2

      @@harshitrautela6585 Honestly, DP. Because I feel its problems are more interesting than graphs and I generally like recursion more. Also, when Striver teaches it you really feel ADDICTED. It's soooo much more immersive than graphs.
      But it's up to you. The disadvantage of going with DP is you have to complete the recursion series first as a prerequisite, and it's longer than the graph series.

    • @Josuke217
      @Josuke217 14 днів тому

      ​@@tasneemayham974I learned recursion from love Babbar but I still suck at it , is Striver's recursion playlist good? Also should I make notes or just learn the topic and apply it? I am asking this because I am confused and don't know how to move forward

    • @tasneemayham974
      @tasneemayham974 12 днів тому +1

      @@Josuke217 I don't know Babbar. But I know that once I learned recursion from Striver, I didn't need to open any other UA-cam video. It IS this good. And YESS definitely make notes. I learn and memorize better when I take notes. Learning goes both ways: note-taking and skill application.
      I know how you feel. Currently, I am stuck too. My Graph series Notes were destroyed because of water contact. I am soooo downnn!! 😥😥😥

    • @Josuke217
      @Josuke217 12 днів тому +1

      @@tasneemayham974 thanks , is the recursion series complete? Because someone told me striver has skipped some topics.

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

    Thank you, Striver 🙂

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

    great explanation ! loving this series!!💙💙💙

  • @ramanpareek5218
    @ramanpareek5218 11 днів тому

    Liked the video, notes taken, understood

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

    Best graph explanation🙌🏻🙌🏻

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

    Understood! Great explanation

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

    UnderStood Thanks for this amazing series

  • @fuzi_blossom
    @fuzi_blossom 11 місяців тому +9

    //Thanku so much striver bhaiya for this amazing content ❤
    //I have made a complete gist of this video in the code written below in C++
    #include
    using namespace std;
    int main()
    {
    // Graph is a finite set of vertices and edges
    // total degree of undirected graph=2*Total edges
    // for directed graph degree is represented in terms of indegree and outdegree
    //degree of a vertex is defined as the no of edges attached with it
    int n, m;
    cout > n;
    cout > m;
    vector adj(n + 1, vector(m + 1, 0));
    vector adj_list[n + 1];
    for (int i = 1; i > v1 >> v2>>wt;
    adj[v1][v2] = wt;
    adj[v2][v1] = wt;//remove this line for directed graph
    adj_list[v1].push_back({v2,wt});
    adj_list[v2].push_back({v1,wt});//remove this line for directed graph
    }
    //---------ADJACENCY MATRIX-------------------//
    // space complexity for undirected graph= O(V*V)
    // space complexity for directed graph : O(V*V)
    cout

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

    US , Excited for learning graph

  • @udityakumar9875
    @udityakumar9875 Рік тому +19

    adjacency list is vectoradj. right? and not just 1d vector

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

      Yeah same doubt

    • @shivgoyal103
      @shivgoyal103 4 місяці тому +1

      han bhai same doubt mera bhi .

    • @ritabhsharma6627
      @ritabhsharma6627 3 місяці тому +37

      Its not a 1-D vector. Its aa array of vector.
      see it this way.
      How a 1-D vector is declared : vector adj(n+1);
      How an array of vectors is declared : vector adj[n+1];
      Do you observe the difference between ( ) and [ ] ? Now you do :D

    • @harsha4048
      @harsha4048 Місяць тому

      ​@@ritabhsharma6627🙌

    • @VivekKumar-kf8yc
      @VivekKumar-kf8yc 22 дні тому

      @@ritabhsharma6627 Thank you so much. I could never understand how he was able to store a list in a vector. Thanks for clearing my doubt.

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

    just awesome pure gold

  • @Sarkar.editsz
    @Sarkar.editsz Рік тому

    Thanks a lot dear brother ❤❤ , understood fully

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

    Understood Sir, Thank you very much

  • @user-bt6mh9ez3u
    @user-bt6mh9ez3u Місяць тому

    Awesome Video..understood everything

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

    @7:16 Time complexity to store the adjacency matrix would be O(m) and not O(n)

  • @bhavkushwaha
    @bhavkushwaha 20 днів тому

    Thankyou Striver, Understood!

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

    Understood Bhaiya
    We can also use this for representing adjacency list:
    unordered_map list

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

    understood, ty, u r the best

  • @akhirulislam4079
    @akhirulislam4079 Рік тому +162

    I feel the matrix should be like adj[n+1][n+1] not adj[n+1][m+1]

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

      yes this right

    • @ProSol-im6zn
      @ProSol-im6zn Рік тому

      Can u say
      How do u know those matrix

    • @ProSol-im6zn
      @ProSol-im6zn Рік тому

      I don't have a proper idea about adj[n+1]

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

      Ya I wasss about to comment this

    • @SsjRose26
      @SsjRose26 Рік тому +8

      ​@@ProSol-im6znbro, if there no of edges depends upon the no of nodes, so we need adj[n+1][n+1], total of n*2 edges possible, what he typed was a mistake in the video

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

    Understood Bhaiya 👍

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

    Understood. Thanks a lot.

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

    Great explanation

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

    understood. Thank you

  • @PRALAY.THAKUR
    @PRALAY.THAKUR 11 місяців тому +1

    very nice explanation

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

    understood very well...

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

    great explanation

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

    UNDERSTOOD!

  • @VarunKaushal-zx9zq
    @VarunKaushal-zx9zq 5 днів тому

    Thank you so much

  • @itsmeakash_
    @itsmeakash_ Рік тому +25

    6:42 why is the matrix is [n+1][m+1] but previously u told [n+1][n+1]?

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

      because in total, there are only n vertices. we dont care about the number of edges here as we can store any edge in the matrix format.

    • @mahaprasadm9770
      @mahaprasadm9770 Рік тому +5

      I think it's a typing mistake.

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

      @@dravitgupta7927 maybe I was unclear in what I meant. I meant that (n+1)(n+1) should be the size, because the number of edges(m) don't matter, but the number of vertices(n) matters. Try reading my old comment once again.

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

      @@ArnabJhaYT Got it👌.

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

      @@ArnabJhaYT yes number of edges won't matter here

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

    understoood!

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

    understood, thanks

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

    Understood!

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

    understood bhaiya.

  • @ANURAGSINGH-nl2ll
    @ANURAGSINGH-nl2ll 10 місяців тому

    understood thank you 🙂

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

    Awesome!

  • @niyamaliyakkal
    @niyamaliyakkal 3 дні тому

    understood ❤‍🔥

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

    understood sir🙏❤🙇‍♂

  • @sujalgupta6100
    @sujalgupta6100 Рік тому +8

    Okay, I was watching your previous playlist yesterday , and in that you said space complexity of Adjacency list is O(V+2E) which i didn't understood.
    Now, I came across this video in which it is O(2E) and I understood it. I know they are almost same but I want to know why did we add V in the space complexity in the old video .

    • @takeUforward
      @takeUforward  Рік тому +21

      Yes, I went through all the comments of those videos, and making sure I cover things which people were having doubts 😅
      The addition of V was for the list creation. The list itself takes N space.

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

    Understood 💥

  • @niteshsaxena1066
    @niteshsaxena1066 Місяць тому

    awesome video

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

    Thank you sir

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

    incredible

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l 3 місяці тому

    Thank you Bhaiya

  • @AbhishekThakur-gz6ul
    @AbhishekThakur-gz6ul 2 роки тому

    Understood ☺️😄

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

    understood!!

  • @KartikeyTT
    @KartikeyTT 23 дні тому

    tysm sir

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

    Understood...
    😊

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

    Understood 😇

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

    Understoood!!!!

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

    2/56 done (3.12.22)

  • @nasimnajand9697
    @nasimnajand9697 8 місяців тому

    Thanks in advance

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

    UNDERSTOOD

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

    understood❤

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

    understood!

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

    understood striver :)

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

    understood.

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

    15:20 so for this it would be: vector adj[n+1] .... right?

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

      no it should be vector adj(n+1);

  • @user-sp9rg7if3i
    @user-sp9rg7if3i 20 днів тому

    @takeUforward
    how to solve if node is negatives??
    like how you represents {(-1 --> 3),

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

    understood

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

    Understood!!

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

    Best videos

  • @sairammurthy6121
    @sairammurthy6121 Місяць тому

    understood :)

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

    Understood

  • @vani.sharmaa
    @vani.sharmaa Рік тому +5

    vector adj[n+1] basically means a vector of arrays right? so can we also declare it as vector of vectors?

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

      Yes, which is adjacency matrix but it takes more space

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

      @@rahulshah2685 no its right , vector[] is array of vector i.e. 2 d array

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

      @@mohakhiphop well vector of vector will take more space if we already declare the size. But the space will be same as vector adj[] if we store in a way so that it doesn't take extra space.

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

      @@DevanshuAugusty yep true💯

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

    vector adj[n+1];
    means => vector adj(n+1);
    Correct me if I am wrong?

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

      something i got stuck on myself, didn't notice the square brackets

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

      it's a vector of array. Try to read it from right to left. At each index there is an empty vector.

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

      when we declare an array of integers of size n, we say int arr[n] so we say the datatype is int. Here, we want to create an array of vectors (of type int) hence, vector arr[n+1] of size n+1.

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

      @@tanishgupta7879 you mean array of vectors

  • @slemanabbas7720
    @slemanabbas7720 4 дні тому

    I am very lucky because I found you❤🎉🎉

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

    Understood

  • @nathonluke4058
    @nathonluke4058 Рік тому +10

    Hi Loved it... Great Explanation from scratch.
    And also as i read your community post. I think the audio quality has changed. In L1 the audio quality was kind of good, but in this there is a lot of disturbance. Also i liked the red colored Writing (specially when it fades after explaning) Loved the details.♥️♥️♥️

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

      his explanition is the worst ever, kunals, shardha didis explination is far better than his

  • @varunkumar-vs5wc
    @varunkumar-vs5wc 8 місяців тому

    thank u

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

    what are we going to do if, in a graph, I have just two nodes and the value is 1 and 10^5 then we won't have the index 10^5 with us to fill!

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

    Thank you very much. You are a genius.

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

    here we go

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

    Understood.

  • @ashishparmar762
    @ashishparmar762 7 місяців тому +1

    00:03 Learn how to represent a graph in C++ or Java
    02:05 Learn how to store edges in a graph using an adjacency matrix or a list.
    04:07 Creating an adjacency matrix to represent edges between nodes
    06:09 Storing a graph using adjacency list takes less space than n square method
    08:15 Adjacency list stores neighbors of a node
    10:12 Using adjacency list for graph storage
    12:22 Learned how to store graphs using adjacency list and matrix
    14:13 Store weights in pairs instead of single integers
    Crafted by Merlin AI.

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

    Nice

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

    Happy teachers day

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

    awsmmmmmmmm

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

    Understood👍

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

    understood ...

  • @111rhishishranjan2
    @111rhishishranjan2 Рік тому

    can anyone tell me what does one way indexing mean

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

    can anyone please explain me what is zero bases and 1 based node??

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

    does this playlist also contains trees?

  • @valendradangi1822
    @valendradangi1822 2 місяці тому +2

    Bhiya at 7:10 adjacency matrix should be of (n+1)*(n+1) size and not (n+1)*(m+1).

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

    Bhaiya itna deep kisi ne nhi samjhaya "Understood😉" Maja aa gaya

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

    Hey, why didn't we use 2D-vector in place of this?
    Creating array of vectors looks confusing.

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

      Array of vectors takes lesser space!

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

      @@takeUforward is it because of double the size property?
      What if we define size of 2d-vector beforehand?
      Something like below:
      vector adjList(n+1, vector(m+1))
      Only asking this because array of vectors was not so intuitive to me atleast :')

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

    Got it

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

    For adjacency list, shouldn't it be vector< vector > adj(n+1) ; ???

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

      vector adj[n+1]- This is not 1D Vector. This is array of Vectors. Here (n+1) are vectors. In an array of vectors, each element (or index) of the array is itself a vector.
      vector adj(n+1); - This is 1D vector. Here we only 1 vector having (n+1) elements.
      This is due to the difference between ( ) and [ ].

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

      @@shivanibaliyan7276 I did not notice the third bracket at first. Yes it is a Vector of Arrays

  • @TON-108
    @TON-108 4 місяці тому

    i started graph but still got confused in this 👇🏼
    vector v[n] and vector v(n) are they same ??? 😭

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

    he teach well