0

I have a problem where I need to implement Dijkstra's algorithm for Single Source Shortest Path Problem with Binary Heaps. The running time should be O(ElogV).

Here is the code for reading in from a scanner:

try {
        Scanner sc = new Scanner(new File("../SOME_TEXT_FILE.txt"));
        String line = sc.nextLine();
        String[] ne = line.split(" ");

        nodes = Integer.parseInt(ne[0].split("=")[1]);
        edges = Integer.parseInt(ne[1].split("=")[1]);

        constructGraph(sc);

The issue happens when the constructGraph(sc) method is called.

Here's that method:

    static void constructGraph(Scanner sc) {
    adjList = new ArrayList[nodes];

    for (int i = 0; i < nodes; i++)
        adjList[i] = new ArrayList<>();

    for (int i = 0; i < nodes && sc.hasNext(); i++) {
        String edge;
        String n = sc.nextLine();
        while (sc.hasNext() && !(edge = sc.nextLine()).isEmpty()) {
            String[] e = edge.trim().split(" ");
            int from, to, weight;

            to = Integer.parseInt(e[0]);
            weight = Integer.parseInt(e[1].trim());
            adjList[Integer.parseInt(n)].add(new Edge(to, weight));
            adjList[to].add(new Edge(Integer.parseInt(n), weight));
        }
    }
}

The error tells me that the issue is in the line that says

weight = Integer.parseInt(e[1].trim());

Here is a sample of the input coming from the text file:

n=1000 m=8544
0
    25    244
   108    275
   140    273
   159    313

1
    24    187
    43    182
    65    331
   155    369
   182    222

2
    31    504
    35    403
   176    249
   229     68

1 Answer 1

1

Because there are multiple spaces between the two numbers you have to split using a different regex

String[] e = edge.trim().split("\\s+");

Splitting "1 2" using split(" ") will produce an array of size 3 with values ["1", "", "2"] where the middle element is the empty string delimited by the left and right space character. Using \\s+ you are saying that you want to split sequences separated by a sequence of whitespace characters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.