I have an assignment on Dijkstra's algorithm, but the question has me confused about the input. It asks me to find shortest and second shortest paths, and that part I have figured out, but how do I even start with the graph has me troubled. The question says the input has to be read from a file and the file contains the number of nodes and the weight between two nodes. Weight between two nodes should be 1 to 9, and can use 0 to indicate a path that doesn't exist. Now my question is what has to be the contents of the file? I was able to understand Dijkstra's algorithm where the input was a 2d array that represents the graph. Can someone clarify what is expected from this question? Like what the source file should contain.
1 Answer
You are probably supposed to create file like this: (example - there are many ways to do it)
4 # number of nodes (from 1 to 4)
1 2 3 # means edge from node 1 to node 2 with weight 3
2 3 1 # means edge from node 2 to node 3 with weight 1
...
this would correspond to 2d matrix like this:
0 3 0 0
0 0 1 0
0 0 0 0
0 0 0 0
(i,j)is the weight between Nodeiandj. When it is an undirected graph it is a symmetrical matrix. If there is no path fromitojuse 0.