交流|链式前向星存图 模板
1041
2021.09.02
发布于 未知归属地

代码模板

int N = 10; // 最大节点数
int M = 100; // 最大边数

// 链式前向星存储结构,其中edge和to都是可选的,按实际情况选择
// 也可以将edge和to合入一个类中
int[] head = new int[N]; // head[n] 表示编号n的节点最新一条边的索引
int[] edge = new int[M]; // edge[i] 表示索引为i的边的权重(长度)
int[] to = new int[M];   // to[i] 表示索引为i的边的终点索引
int[] next = new int[M]; // next[i] 表示索引为i的边 下一条同起点的边的索引,用于找到同起点的下一条边
int i = 0; // 边索引

Arrays.fill(head, -1);   // 先设置所有编号节点都没有边(-1表示该节点没有边)

// 添加一条新的边,索引为i,起点为a,终点为b
void add(int a, int b) {
    to[i] = b;          // 索引为i的边终点为b
    next[i] = head[a];  // 该边下一条同起点边的索引为head[a]
    head[a] = i++;      // 更新起点a最新的一条边索引为i
}

// 遍历所有从a发出的边
// 从head[a]取出a节点最新一条边的索引idx,开始遍历。
// 每次通过next[idx]获取以该节点为起点的下一条边的索引
// 直到下一条边的索引为-1,即没有下一条边
for (int idx = head[a]; idx != -1; idx = next[idx]) {
		// 取出该索引对应的边的终点
    int end = to[idx];
    // 取出该索引对应的边的权重
    int val = edge[idx];
}

参考资料

https://leetcode-cn.com/problems/all-nodes-distance-k-in-binary-tree/solution/gong-shui-san-xie-yi-ti-shuang-jie-jian-x6hak/

https://blog.csdn.net/qq_35501306/article/details/106276964

https://zhuanlan.zhihu.com/p/343092172

评论 (0)