簡體   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