添加 a->b 路径代码:
int tot = 0; //全局变量,表示第几条路径
int head[LEN] = {0};
int next[LEN] = {0};
// 存储 a->b 路径
void add(int a, int b) {
++tot; // 路径标号,第几条路径
next[tot] = head[a];
head[a] = tot;
des[tot] = b; //存储终点,表示 第tot条路径 的终点是b
}
//head[] 的数组下标为地点
//next[] 的数组下标为第几条路径
//des[] 的数组下标为第几条路径
//head[] next[] 数组里的元素在创建时必须初始化为零
假设插入如下路径:a->b, a->c, a->d, b->e, a->e
先初始化 head,next 数组,都初始化为 0,
head[ a ] = 0,head[ b ] = 0,... ,head[ e ] = 0
next[ a ] = 0,next[ b ]=0,... ,next[ e ] = 0 (注意 a, b, c, d, e 可以化作数字 1, 2, 3, 4, 5)
插入 a->b: ++tot = 1(第1条路径), next[ 1 ] = head[ a ] = 0, head[ a ] = tot = 1, des[ 1 ] = b(终点是b)
插入 a->c: ++tot = 2(第2条路径), next[ 2 ] = head[ a ] = 1, head[ a ] = tot = 2, des[ 2 ] = c(终点是c)
插入 a->d: ++tot = 3(第3条路径), next[ 3 ] = head[ a ] = 2, head[ a ] = tot = 3, des[ 3 ] = d(终点是d)
插入 b->e: ++tot = 4(第4条路径), next[ 4 ] = head[ b ] = 0, head[ b ] = tot = 4, des[ 4 ] = e(终点是e)
插入 a->e: ++tot = 5(第5条路径), next[ 5 ] = head[ a ] = 3, head[ a ] = tot = 5, des[ 5 ] = e(终点是e)
遍历以 a 为起点的所有路径:
for(int i = head[a]; i; i = next[i]){
}
1、遍历以 a 为起点的路径:
i = head[ a ] = 5;
i = 5, des[ 5 ] = e (终点是e,路径:a -> e) i = next[ 5 ] = 3; //第5条路径
i = 3, des[ 3 ] = d (终点是d,路径:a -> d) i = next[ 3 ] = 2; //第3条路径
i = 2, des[ 2 ] = c (终点是c,路径:a -> c) i = next[ 2 ] = 1; //第2条路径
i = 1, des[ 1 ] = b (终点是b,路径:a -> b) i = next[ 1 ] = 0; //第1条路径
i = 0 ( 退出循环 )
2、遍历以 b 为起点的路径:
i = head[ b ] = 4;
i = 4, des[ 4 ] = e (终点是e,路径:a -> e) i = next[ 4 ] = 0; //第4条路径
i = 0 ( 退出循环 )
3、假设遍历以 e 为起点的路径,当然并不存在以 e 为起点的路径,在初始化 i = head[ e ] = 0,就直接退出遍历循环了
读者还可以自己添加一个 len[ ] 数组存储每条路径的长度,数组下标为 tot ( 路径标号 ) ( 和 des[ ] 数组用法一致 )