相邻列表到定向图

时间:2016-03-25 01:21:25

标签: java graph nodes dijkstra

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

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

使用模式vertexname adj.vertex weight adj.vertex weight .....

我找到了一些填充图形的示例代码:

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

开始的代码的链接

1 个答案:

答案 0 :(得分:1)

[EDITED]

以下是一个代码片段,它将使用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+");