Hi,I am beginner and I want to know what is the fastest way to implementing graphs in C++ for some algorithms of graph(DFS,BFS,.....). Sorry for my poor english.
| # | User | Rating |
|---|---|---|
| 1 | Benq | 3676 |
| 2 | Kevin114514 | 3659 |
| 3 | jiangly | 3640 |
| 4 | turmax | 3450 |
| 5 | tourist | 3382 |
| 6 | strapple | 3360 |
| 7 | Um_nik | 3354 |
| 8 | squareOf105 | 3348 |
| 9 | maroonrk | 3312 |
| 10 | idontwannadothis…e | 3191 |
| # | User | Contrib. |
|---|---|---|
| 1 | Qingyu | 155 |
| 2 | nik_exists | 151 |
| 3 | maspy | 149 |
| 4 | AmShZ | 145 |
| 5 | Um_nik | 143 |
| 6 | Errichto | 139 |
| 7 | BledDest | 136 |
| 8 | adamant | 134 |
| 9 | maroonrk | 132 |
| 10 | cry | 130 |
Hi,I am beginner and I want to know what is the fastest way to implementing graphs in C++ for some algorithms of graph(DFS,BFS,.....). Sorry for my poor english.
| Name |
|---|



I can help you that, using lists!
Thing is you'll get the edges like "there's an edge from node x to node y of cost z". For each edge i, you'll "put" it your graph:
cost[i]=z;
node[i]=y;
next[i]=last[x];
last[x]=i;
At any time, last[x] will remember which is the last edge that goes from node x to another node. When you want to see the neighbors of a node, watch this:
p=last[x];
while(p!=0){
//node[p] is my neighbor
//the cost of the edge between me and node[p] is cost[p]
p=next[p];
}
This works really fast, and it's quite easy after you get it. So you'll need next[EDGES], node[EDGES] and, if the problem specifies, cost[EDGES]. Of course last[NODES]. Remember that in a undirected graph you'll need 2 edges for each step: one that goes form x to y, and one that goes from y to x, and you'll have double number of edges. Got it?
thanks
Use adjacency list representation. U can use vector to easily maintain your adjacency list. For example lest's assume a graph with n nodes and m edges, the edges are given in the form (a b) where there is a directed edge from a to b. U can do the following
traversing the adjacency list of any node is easy;
For sparse graphs you can use static arrays to index the edges:
For me, the easiest and shortest way is to use a vector and range for loops from C++11.
Declaration of adjacency list:
Add directed edge u->v:
Process edges of node v:
Of course, if edges also have a weight/capacity associated with them, you'd declare a
pair<int,int>vector instead.I hope I've been of help.
I think for adjacency linklist :
for weighted graph :
vector<pair<int,int> > Graph[number_of_vertex];for unweighted graph :
vector Graph[number_of_vertex];for adjacency matrix :
for weighted and unweighted : use 2D array
int Graph[number_of_vertex][number_of_vertex];