简体   繁体   English

如何用Java中的文本文件为Dijkstra最短路径算法生成加权图的图?

[英]How to generate a map of weighted graph for Dijkstra’s Shortest Path Algorithm from a text file in Java?

I have a text file "NYRoadNetwork.txt" which contains the following information of a weighted graph: 我有一个文本文件“ NYRoadNetwork.txt”,其中包含加权图的以下信息:

The first row represents the number of nodes in the graph, ie 30 第一行代表图中的节点数,即30

The second row represents the number of edges connecting any two nodes in the graph, ie 17 第二行表示连接图中任意两个节点的边数,即17

The remains are the weight of edges connecting any two nodes, eg. 剩余部分是连接任意两个节点的边的权重。 "0 1 2" in third row means the weight of edge connecting node 0 and 1 is 2. 第三行中的“ 0 1 2”表示边缘连接节点0和1的权重为2。

30   
17   
0 1 2   
2 3 0    
4 5 1   
6 7 3   
8 9 4   
8 10 3  
0 11 2  
1 12 1  
13 14 3  
15 16 4   
17 18 2   
19 20 3   
19 21 3   
22 23 6    
24 25 1           
26 27 1            
28 29 1    

Now, my question is, instead of input each node and edges one by one, how can I write a java code to generate the complete graph after reading the data from the text file? 现在,我的问题是,从文本文件读取数据后,如何编写Java代码以生成完整图形,而不是输入每个节点和每个边缘?

FYI, this is my part of original java code which I want to modify. 仅供参考,这是我要修改的原始Java代码的一部分。

    // mark all the vertices
    Vertex 0 = new Vertex("0");
    Vertex 1 = new Vertex("1");
    Vertex 2 = new Vertex("2");
    Vertex 3 = new Vertex("3");
    Vertex 4 = new Vertex("4"); ......

    // set the edges and weight
    0.adjacencies = new Edge[]{ new Edge(1, 2) };
    0.adjacencies = new Edge[]{ new Edge(11, 2) };
    1.adjacencies = new Edge[]{ new Edge(12, 1) };
    2.adjacencies = new Edge[]{ new Edge(3, 0) };
    4.adjacencies = new Edge[]{ new Edge(5, 1) };
    6.adjacencies = new Edge[]{ new Edge(7, 3) }; .......

You can use BufferedReader to read a line from a file. 您可以使用BufferedReader 文件中读取一行

After that use String.split() method to split a line into an array of string. 之后,使用String.split()方法将一行拆分为字符串数组。

I suggest you, to go through Java APIs before asking this type of questions. 我建议您在询问此类问题之前,先通读Java API。

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

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