GRAPH help

Thanks for spending time to view this !
Btw currently Iam learning graph theory (beginner). But i am struggling in storing the graph like, if the edges given are from 0, 1, 2, 3, 4… through N then i will be storing it in O(1) by direcctly accessing the i th index.

 graph[0] -> 1 -> 2 -> 3
 graph[1] -> 0 -> 3 -> 4

and so on…

But what if i get vertices like A,B,C,D … or something like 21, 35, 67, 89 (just for example). In such cases how can i access the index of those big valued vertices or in case of characters how can i even store it in ADJACENCY LIST.
0 → graph[A] → B → C
1 → graph[B] → A → D
how???

I think you can use vector<vector<char> > adjL[250] , then this should be fine adjL['A'].push_back('B')

1 Like

If there are bigger numbers, you can use map. Not only for Large numbers, map can be used for any data types the language supports. Think about some real-life situation: Cities are nodes and the roads are edges. You can still use map in CPP and Java or dict in Python.

# Python Code
graph = defaultdict(list)
graph['Hyderabad'].append('Secunderabad')
graph['Mumbai'].append('Kolkata')
// CPP Code (not sure)
#include <bits/stdc++.h>
using namespace std;

int main()
{
    map<string, vector<string>> graph;
    
    graph["Hyderabad"].push_back("Secunderabad");
    
    graph["Mumbai"].push_back("Kolkata");
    
    cout << graph["Hyderabad"][0] << endl;

    return 0;
}

1 Like