Introduction
Terminology:
- If you are at a Node then the nodes connected to that node are called Neigbours
Types and Methods of Input
Non Weighted Graphs
In Non Weighted Graphs the edge value is 1.
There are two types of graphs:
-
Undirected
In undirected graph the relation is two ways i.e. u --> v and v --> u -
Directed
In directed graph the relation is one way i.e. u --> v only
There are two methods of input:
- Adjacency Matrix
int arr[n+1][n+1]; // n is number of nodes
for (i to m) { // m is number of edges
int r, c;
cin >> r >> c;
arr[r][c] = 1;
arr[c][r] = 1; //! Remove this line for Directed Graph
}
- Adjacency List
vector<int> arr[n+1]; // n is number of nodes
for (i to m) { // m is number of edges
int r, c;
cin >> r >> c;
arr[r].push_back(c);
arr[c].push_back(r); //! Remove this line for Directed Graph
}
Weighted Graphs
The edges also have weights
- For Adjacency Matrix:
int arr[n+1][n+1]; // n is number of nodes
for (i to m) { // m is number of edges
int r, c, wt;
cin >> r >> c >> wt;
arr[r][c] = wt;
arr[c][r] = wt; //! Remove this line for Directed Graph
}
- For Adjacency List:
vector<pair<int,int>> arr[n+1]; // Notice we have used pair here i.e. we will store both the node and the weight
for (i to m) { // m is number of edges
int r, c, wt;
cin >> r >> c >> wt;
arr[r].push_back({c, wt);
arr[c].push_back({r. wt}); //! Remove this line for Directed Graph
}