Java代码--存图方式链式前向星

package template;
import java.util.*;
public class LianShiQianXiangXing {
	//以有向带权图为例----那么让一条无向边更新两个head指向
	static int n,m;
	static boolean []flagg=new boolean[1005];
	static int[]head=new int[1005];//以顶点i为起点的第一条边的下标
	static class Edge{
		int to;//边的终点值
		int w;//权值
		int nextt;//下一个同起点边下标的值
	}
	static Edge[]edges=new Edge[1000005];
	public static void printt() {
		//遍历图
		for(int i=1;i<=n;i++) {//遍历起点
//			if(flagg[i]==true)continue;
			System.out.print(i+" ");
//			flagg[i]=true;
			for(int i0=head[i];i0!=-1;i0=edges[i0].nextt) {
				//遍历边
//				if(flagg[i0]==true)continue;
				int too=edges[i0].to;
				System.out.print(too+" ");
//				flagg[too]=true;//标记
			}	
			System.out.println();
			
		}
		
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		m=sc.nextInt();
//		开始未读入边时,全部边下标初始化为-1
		Arrays.fill(head, -1);
		int s=0,e=0,w=0;
		for(int i=1;i<=m;i++) {
			edges[i]=new Edge();
			s=sc.nextInt();
			e=sc.nextInt();
			w=sc.nextInt();
		   edges[i].to=e;
		   edges[i].w=w;
		   
		   //接下来两步相当于头插法
		   edges[i].nextt=head[s];//以s为起点的下一条边的下标
		   head[s]=i;
		   
		}
		printt();
		
	}

}

该方法适用于有向图和无向图,另外对于图是否连通也无需考虑

介绍关键思路:和邻接表是类似的,都是需要找到以某个点为起点的所有边然后串起来

不过该方法适用的是数组,相当于静态链表

加上注释的flagg部分的代码,可以遍历图检验是否存图成功

可根据下图理解代码

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务