链式前向星(Java描述)
什么是链式前向星?
1.链式前向星是一种图的存储方式
2.比起二维数组(邻接矩阵)存储能节省空间
3.比起邻接表更简便
视频资源:https://www.bilibili.com/video/BV1mJ411S7BB?from=search&seid=7140927744120808408
链式前向星模板
public class 模板 { //保存边的类 public static class Edge{ int to; //到那个点 int w; //权值 int next; //下一条边在 edge数组中的索引 public Edge(int to, int w, int next) { //构造方法 super(); this.to = to; this.w = w; this.next = next; } } static int edge_index = 1; //edge数组的下一个空位的下标,注意得从1开始 public static void main(String[] args) { // TODO Auto-generated method stub int[] head = new int[100]; //从head数组可以取到每个点对应的所有边 Edge[] edgeArr = new Edge[100]; //存储边的数组 } //添加边的方法 public static void add(Edge[] edgeArr,int u,int v,int w,int[] head) { edgeArr[edge_index] = new Edge(v, w, head[u]); head[u] = edge_index;//head数组里面保存的是第一个边在edge数组中的索引索引 edge_index++;//指向空节点 } //通过顶点索引(index)获取其所有边 public static void getAllEdge(int index,int[] head,Edge[] edgeArr) { for(int i=head[index];i!=0;i=edgeArr[i].next) { //遍历获得所有边在edgeArr中的索引 Edge edge = edgeArr[i]; //获取一条边 } } }

浙公网安备 33010602011771号