简体   繁体   中英

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:

The first row represents the number of nodes in the graph, ie 30

The second row represents the number of edges connecting any two nodes in the graph, ie 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.

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?

FYI, this is my part of original java code which I want to modify.

    // 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.

After that use String.split() method to split a line into an array of string.

I suggest you, to go through Java APIs before asking this type of questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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