gpt4 book ai didi

java - 有向图的邻接表

转载 作者:行者123 更新时间:2023-12-01 10:09:38 25 4
gpt4 key购买 nike

我正在开发一个实现 Dijkstra 的最短路径算法的程序。它以文本文件中的邻接列表的输入开始,格式为:

1 2 1 3 1
2 4 2
3 2 2 5 4
4 3 3 5 3
5 1 4

使用模式 vertexname adj.vertexweight adj.vertexweight.....

我找到了一些填充图表的示例代码,如下所示:

private static final Graph.Edge[] GRAPH = {
new Graph.Edge("a", "b", 7),
new Graph.Edge("a", "c", 9),
new Graph.Edge("a", "f", 14),
new Graph.Edge("b", "c", 10),
new Graph.Edge("b", "d", 15),
new Graph.Edge("c", "d", 11),
new Graph.Edge("c", "f", 2),
new Graph.Edge("d", "e", 6),
new Graph.Edge("e", "f", 9),};

这可行,但正如我所说,我需要从格式与上述类似的文本文件中填充此数据。我遇到的麻烦是每行的数据量没有设定限制。一个节点可以附加一个或无限多个其他节点。我正在尝试提出一个能够解决这个问题的解决方案。到目前为止,我在我的主要方法中进行了粗略的尝试:

Scanner scanner = new Scanner(new File(filename));
while(scanner.hasNextInt()){
String source = scanner.next();
String to = scanner.next();
int weight = scanner.nextInt();
Graph.Edge edge = new Graph.Edge(source, to, weight);
if(scanner.hasNext()){
to = scanner.next();
weight = scanner.nextInt();
Graph.Edge edge2 = new Graph.Edge(source, to, weight);
}
}

当我尝试运行这个程序时,我在 Scanner.throwfor、Scanner.next 和我的主类中的这一行得到 NoSuchElementException:

String to = scanner.next();

我知道我的尝试目前在语法上并不完全正确,但我是否走在寻找解决方案的正确道路上?另外,我正在寻找什么关键的东西或者可以让这件事变得更容易吗?谢谢!

编辑:这是我从 http://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java 开始的代码的链接

最佳答案

[已编辑]

下面是一个代码片段,它将使用 Edges 实例填充 ArrayList:

List<Graph.Edge> list = new ArrayList<Graph.Edge>();

try {
Scanner scanner = new Scanner(new File(filepath));
while(scanner.hasNextLine()){
String source = scanner.findInLine(NAME);
if (source != null) {
while(true) {
String to = scanner.findInLine(NAME);
if (to == null) {
break;
}
int weight = Integer.valueOf(scanner.findInLine(WEIGHT));
list.add(new Graph.Edge(source, to, weight));
}
}
scanner.nextLine();
}
} catch (Exception e) {
e.printStackTrace();
}

它使用hasNextLinefindInLine一次处理一行,以确保正确创建具有相同source值的边.

NAMEWEIGHT 模式由以下常量定义:

static final Pattern NAME   = Pattern.compile("\\w+");
static final Pattern WEIGHT = Pattern.compile("\\d+");

关于java - 有向图的邻接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com