第四周作业——图的表示

作业要求:给定图数据文件(tinyG.txt),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。类名:GraphRepresentation



用java实现无向图的表示,代码如下:

/**
 * 无向图的表示
 */
public class GraphRepresentation{
			
	//vertex,顶点数目
	private int v;
	//edge,边数目
	private int e;
	//邻接矩阵
	private int [][] matrix ;
	
	/**
	 * 初始化
	 * @param v 顶点数目
	 * @param e 边数目
	 */
	public GraphRepresentation(int vartex, int edge){
		this.v = vartex;
		this.e = edge;
		this.matrix = new int[v][v];
	}	
	
	//两个顶点间存在边,设置矩阵值
	public void addEdge(int v1, int v2){
		matrix[v1][v2] = 1;
		matrix[v2][v1] = 1;
	}
	
	//获取邻接矩阵
	public int[][] getAdjacencyMatrix(){ return matrix; }
	
}


测试代码:

	public static void main(String[] args){
		String path = "D:\\graph";
		
		try(Scanner scanner = new Scanner
			(GraphRepresentation.class.getClassLoader().getResourceAsStream("tinyG.txt"));
			PrintWriter out = new PrintWriter(new File(path, "tinyG_matrix.txt"));){
			
			//第一行的数字是顶点的数目
			int v = scanner.nextInt();
			//第二行的数字是边的数目
			int e = scanner.nextInt();
			GraphRepresentation graph = new GraphRepresentation(v, e);
			
			//读取每条边对应的两个顶点,设置邻接矩阵的值
			for (int i = 0; i < e; i++) {				
				int v1 = scanner.nextInt();
				int v2 = scanner.nextInt();
				graph.addEdge(v1, v2);
			}
			
			//计算无向图的邻接矩阵,并将其写到文件中
			int[][] matrix = graph.getAdjacencyMatrix();
			for(int i=0; i<v; i++){
				for(int j=0; j<v; j++){
					out.print(matrix[i][j] + "\t");
				}
				out.println();
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
		
		System.err.println("邻接矩阵已成功写到磁盘上...");
		
	}



测试结果:



温馨提示: 今天愚人节,如果程序有bug,那可能是我在和您开玩笑...


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值