Prim和Kruskal算法

Prim和Kruskal算法

通过让边类实现comparable接口实现排序,treeSet可以排序并且去重

结点类

class Vertex {
		String name;// 顶点名称
		Edge next;// 下一条边(第一个为顶点 后面都是边)

		public Vertex(String name) {
			this.name = name;
		}

		// 获取结点的出边
		public TreeSet<Edge> outEdges() {
			//List<Edge> list = new LinkedList<>();
			TreeSet<Edge> treeSet = new TreeSet<>();
			Edge edge = this.next;
			while (edge != null) {
				treeSet.add(edge);
				edge = edge.next;
			}
			//Collections.sort(treeSet);
			return treeSet;
		}

		@Override
		public String toString() {
			return "Vertex [name=" + name + "]";
		}

	}

边类

class Edge implements Comparable<Edge>{
		String name;// 指向的顶点名称
		int weight;// 权值
		Edge next;// 下一条边(链表上)

		public Edge(String name, int weight) {
			this.name = name;
			this.weight = weight;
		}

		@Override
		public String toString() {
			return "Edge [name=" + name + ", weight=" + weight + "]";
		}

		@Override
		public int compareTo(Edge o) {
			if(this.weight!=o.weight)
				return this.weight-o.weight;
			else
				return this.name.compareTo(o.name);
		}
	}

Prim算法

/**
	 * 普利姆算法
	 * @param name 开始结点
	 * @return
	 */
	public Set<Edge> prim(String name) {
		Set<Vertex> addVertex = new HashSet<>();//存放经过的结点
		Set<Edge> addEdge = new HashSet<>();//存放经过的边
		Vertex beginVertex = vertexMap.get(name);
		if (beginVertex.next == null)
			return null;
		addVertex.add(beginVertex);
		TreeSet<Edge> treeSet = new TreeSet<>(beginVertex.outEdges());
		while(!treeSet.isEmpty()&&addVertex.size()<vertexMap.size()) {
			Edge edge = treeSet.pollFirst();
			if(addVertex.contains(vertexMap.get(edge.name))) continue;
			addEdge.add(edge);
			addVertex.add(vertexMap.get(edge.name));
			treeSet.addAll(vertexMap.get(edge.name).outEdges());
		}
		return addEdge;
	}

Kruskal算法

public Set<Edge> kruskal(){
		TreeSet<Edge> allEdges = getAllEdges();
		int size=vertexMap.size()-1;
		if(size==-1) return null;
		HashSet<Edge> addEdge = new HashSet<>();
		UnionFind<Vertex> uf = new UnionFind<>();
		Iterator<Vertex> it = vertexMap.values().iterator();
		while(it.hasNext()) {
			uf.makeSet(it.next());
		}
		while(!allEdges.isEmpty()&&addEdge.size()<size) {
			Edge edge = allEdges.pollFirst();
			if(uf.isSame(vertexMap.get(edge.beginName), vertexMap.get(edge.endName))) continue;
			addEdge.add(edge);
			uf.union(vertexMap.get(edge.beginName), vertexMap.get(edge.endName));
		}
		return addEdge;
	}
相关推荐
©️2020 CSDN 皮肤主题: 鲸 设计师:meimeiellie 返回首页