Adjacent table
Compared with a non-full graph, the use of an adjacent matrix to store Graph Information wastes a lot of space. At the same time, there will be excessive computing waste of time when finding the shortest path.
Using an adjacent table can save these waste of time.
The following describes the adjacent tables simulated by Arrays:
Define the begin [maxn], end [maxn], DIS [maxn], first [maxn], and next [maxn] arrays.
The example is described as follows:
4 5
1 4 9
4 3 8
1 2 5
2 4 6
1 3 7
Step 1:
|
|
1 |
2 |
3 |
4 |
5 |
|
Begin |
|
|
|
|
|
|
End |
|
|
|
|
|
|
DIS |
|
|
|
|
|
|
First |
-1 |
-1 |
-1 |
-1 |
-1 |
|
Next |
|
|
|
|
|
Step 2:
|
|
1 |
2 |
3 |
4 |
5 |
|
Begin |
1 |
|
|
|
|
|
End |
4 |
|
|
|
|
|
DIS |
9 |
|
|
|
|
|
First |
1 |
-1 |
-1 |
-1 |
-1 |
|
Next |
-1 |
|
|
|
|
Step 3:
|
|
1 |
2 |
3 |
4 |
5 |
|
Begin |
1 |
4 |
|
|
|
|
End |
4 |
3 |
|
|
|
|
DIS |
9 |
8 |
|
|
|
|
First |
1 |
-1 |
-1 |
2 |
-1 |
|
Next |
-1 |
-1 |
|
|
|
Step 4:
|
|
1 |
2 |
3 |
4 |
5 |
|
Begin |
1 |
4 |
1 |
|
|
|
End |
4 |
3 |
2 |
|
|
|
DIS |
9 |
8 |
5 |
|
|
|
First |
3 |
-1 |
-1 |
2 |
-1 |
|
Next |
-1 |
-1 |
1 |
|
|
Step 5:
|
|
1 |
2 |
3 |
4 |
5 |
|
Begin |
1 |
4 |
1 |
2 |
|
|
End |
4 |
3 |
2 |
4 |
|
|
DIS |
9 |
8 |
5 |
6 |
|
|
First |
3 |
4 |
-1 |
2 |
-1 |
|
Next |
-1 |
-1 |
1 |
-1 |
|
Step 6:
|
|
1 |
2 |
3 |
4 |
5 |
|
Begin |
1 |
4 |
1 |
2 |
1 |
|
End |
4 |
3 |
2 |
4 |
3 |
|
DIS |
9 |
8 |
5 |
6 |
7 |
|
First |
5 |
4 |
-1 |
2 |
-1 |
|
Next |
-1 |
-1 |
1 |
-1 |
3 |
Create an adjacent table:
1 nT n, m, I; 2 int begin [6], end [6], DIS [6]; 3 int first [6], next [6]; 4 scanf ("% d", & N, & M); 5 // initialize the first array 6 for (I = 1; I <= N; I ++) 7 first [I] =-1; 8 for (I = 1; I <= m; I ++) 9 {10 scanf ("% d ", & begin [I], & End [I], & dis [I]); 11 next [I] = first [begin [I]; 12 first [begin [I] = I; 13}
Traverse all edges of vertex 1:
1 k=first[1];2 while(k!=-1)3 {4 printf("%d %d %d\n",begin[k],end[k],dis[k]);5 k=next[k];6 }