繁体   English   中英

邻接表到有向图

[英]Adjacency List to Directed Graph

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

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

带有图案顶点名称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开始的代码的链接

[编辑]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM