图论算法 java_求图论算法java实现

展开全部

求图论算法java实现package test;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.HashMap;

import java.util.Map;

import java.util.PriorityQueue;

import java.util.Queue;

public class MinSpanningTree {

class Edge {//内部类定义边的数据结果

int u, v, weight;

}

ArrayList Edges = new ArrayList();

Map nodeFather = new HashMap();

int cnt = 0, nodeCnt = 0;

public MinSpanningTree(String path) {

try {

BufferedReader br = new BufferedReader(new FileReader(path));

String str;

String[] strArray;

while ((str = br.readLine()) != null) {

strArray = str.split("\\s");

Edges.add(cnt, new Edge());

Edges.get(cnt).u = Integer.parseInt(strArray[0]);

Edges.get(cnt).v = Integer.parseInt(strArray[1]);

Edges.get(cnt).weight = Integer.parseInt(strArray[2]);

if (!nodeFather.containsKey(Edges.get(cnt).u)) {

nodeFather.put(Edges.get(cnt).u, Edges.get(cnt).u);//初始化,father[i]=i;

++nodeCnt;

}

if (!nodeFather.containsKey(Edges.get(cnt).v)) {

nodeFather.put(Edges.get(cnt).v, Edges.get(cnt).v);

++nodeCnt;

}

++cnt;

}

br.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public boolean union(int u, int v) {//并操作

int a = find(u);

int b = find(v);

if (a != b) {

nodeFather.put(a, b);

return true;

}

return false;

}

public int find(int x) {//查操作

if (x != nodeFather.get(x)) {

nodeFather.put(x, find(nodeFather.get(x)));

}

return nodeFather.get(x);

}

public ArrayList getMinSpanningTree() {

ArrayList result = new ArrayList();

Queue FsQueue = new PriorityQueue(1000,//设置优先队列,使按边e68a843231313335323631343130323136353331333337383836权值从小到大排序

new Comparator() {

public int compare(Edge EdgeOne, Edge EdgeTwo) {

if (EdgeOne.weight > EdgeTwo.weight)

return 1;

else if (EdgeOne.weight 

return -1;

else

return 0;

}

});

for (int i = 0; i 

FsQueue.add(Edges.get(i));

}

while (!FsQueue.isEmpty()) {//遍历每一条边

Edge Edge = FsQueue.poll();

if (union(Edge.u, Edge.v)) {

result.add(Edge);

} else {

continue;

}

}

return result;

}

public static void main(String[] args) {

MinSpanningTree mstree = new MinSpanningTree("c:/treedata.txt");

ArrayList result = mstree.getMinSpanningTree();

for (int i = 0; i 

System.out.println(result.get(i).u + " " + result.get(i).v + " "+ result.get(i).weight);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值