011带权重的无向边数据类型实现

图学习笔记索引

图学习笔记索引(全部)
001自定义输入流In类实现
002背包数据类型Bag实现
003无向图数据类型实现
004基于图的深度优先搜索
005使用深度优先搜索找图中的所有连通分量
005-1基于深度优先搜索查找图中连通路径
006基于深度优先搜索判断图中是否存在环
007基于深度优先搜索判断一个无向图图是否是一个二分图
008广度优先搜索查找连通图中的最短路径
009有向图数据类型实现
010有向图的可达性
011带权重的无向边数据类型Edge实现
012加权无向图数据类型实现

本文参考《算法(第4版)》

1.带权重的无向边数据类型实现

1)图文件读取
点击文字获取:流读取类In参考链接
从文件中读取图的顶点关系。
tinyEWG.txt文件中的第一行为顶点数,第二行为边数。
第三行到最后是两个相邻的顶点即边的权重:
8
16
4 5 0.35
4 7 0.37
5 7 0.28
0 7 0.16
1 5 0.32
0 4 0.38
2 3 0.17
1 7 0.19
0 2 0.26
1 2 0.36
1 3 0.29
2 7 0.34
6 2 0.40
3 6 0.52
6 0 0.58
6 4 0.93

2)代码实现

 package algorithms.graph;
/*
 * 带权重的无向边数据类型
 * */
public class Edge implements Comparable<Edge>{
    private final int v;
    private final int w;
    private final double weight;
    public Edge(int v, int w, double weight){
    	this.v = v;
    	this.w = w;
    	this.weight = weight;
    }
    public int either(){
    	return v;
    }
    public int other(int vertex){
    	if(vertex == v)      return w;
    	else if(vertex == w) return v;
    	else throw new RuntimeException("Inconsistent Edge");
    }
    public double weight(){
    	return this.weight;
    }
	@Override
	public int compareTo(Edge that) {
		double cmp = this.weight - that.weight;
		if(cmp < 0.0)      return -1;
		else if(cmp > 0.0) return +1;
		return 0;
	}
	public String toString() {
		 return String.format("%d-%d %.2f", v, w, weight);
	}
	public static void main(String[] args) {
		Edge edge1 = new Edge(0, 1, 0.5);
		System.out.println(edge1.v);
		System.out.println(edge1.either());
		System.out.println(edge1.other(0));
		System.out.println(edge1);
		Edge edge2 = new Edge(1, 2, 0.7);
		System.out.println(edge1.compareTo(edge2)); 
	} 
}

输出

0
0
1
0-1 0.50
-1

2.总结

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值