2016-03-25 38 views
0

我正在研究一个实现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重量adj.vertex重量格局.....

我已经发现了一些用于填充这样的图示例代码:

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

+0

我与我的编码尝试目前的思维过程是取文件的前三个整数,因为那里是保证至少有三个整数在一条线上,并把这些放在一个新的边缘。从那里,我尝试使用if来查看行中是否还有更多数据。如果有,那么我将这些数据添加到新的边缘。目前,这似乎只适用于5行整数。 – user3068177

回答

1

将帖子代码

下面的代码片段,将在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+"); 
+0

当我输入这段代码时,我仍然收到大部分相同的错误。编译器不喜欢这行代码String source = scanner.next();这阵子。 – user3068177

+0

您的文件中可能只有空白或空行。当没有更多的标记时,'next()'方法不是很宽容。我已经更新了我的代码片段来处理这个问题。 – cybersam

+0

似乎这样做,谢谢!感谢帮助 – user3068177