Question

Please follow all the instructions and do all the parts (a-d)!

Create a Java program which implements Dijkstra’s shortest path algorithm according to the psueudocode below. Base the design on the weighted graph implementation used in Problem3.java (provided at the bottom). Your program should include the following features:

a. A new method receives a starting vertex index and a target vertex index (e.g. 0 and 4). It computes the shortest distances to all vertexes using Dijkstra’s algorithm. The pseudocode is given below:

b. In the method for (a), print the values of the arrays “allowed” and “distance” at the end of each iteration of the outer loop (after “distance” has been updated).

c. In the method for (a), print the vertexes of the shortest path to the target. If there is no path, the algorithm should still work by printing a warning message. Note that printing the path requires storing the “predecessor” values. The path vertexes should be printed in order, beginning with the starting vertex. To reverse the default order, you may use the Stack class, if desired.

d. A main() method demonstrates the method for (a).

Below is an example of a graph and the expected output for the path from v0 to v4. Though not required, the output below adds some extra messages to indicate the initial values and when the loop is about to be executed.

3 7 0 6 2 5 1 2 8

Below is an example using the same graph for a path from v4 to v0, which is not valid. We know it is not valid because the distance to v0 is Infinity.

Initial values... allowed: false false false false false false distance: Infinity Infinity Infinity Infinity 0.0 Infinity Exe

Problem3.java:


public class Problem3 implements Cloneable {
    private double[ ][ ] edges;
    private Object[ ] labels;

    public Problem3(int n) {
        edges = new double[n][n];
        labels = new String[n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                edges[i][j] = -1.0;
            }
        }
    }

    public void addEdge(int source, int target, double weight) {
        edges[source][target] = weight;
    }

    public double getWeight(int source, int target) {
        return edges[source][target];
    }

    public void printTotalPath(int[] vertex) {
        double weight = 0.0;
        boolean valid = true;
        System.out.print("The path from " + getLabel(vertex[0]));
        for (int i = 1; i < vertex.length; i++) {
            weight += edges[vertex[i-1]][vertex[i]];
            if (!isEdge(vertex[i-1], vertex[i]))
                valid = false;
            System.out.print(" to " + getLabel(vertex[i]));
        }
        if (valid)
            System.out.println(" is " + weight + ".");
        else
            System.out.println(" is not valid.");
    }

    public static void depthFirstPrint(Graph g, int start) {
        boolean[ ] marked = new boolean [g.size( )];

        depthFirstRecurse(g, start, marked);

    }

    public static void depthFirstRecurse(Graph g, int v, boolean[ ] marked) {
        int[ ] connections = g.neighbors(v);
        int i;
        int nextNeighbor;

        marked[v] = true;
        System.out.println(g.getLabel(v));

        for (i = 0; i < connections.length; i++) {
            nextNeighbor = connections[i];
            if (!marked[nextNeighbor])
                depthFirstRecurse(g, nextNeighbor, marked);
        }
    }

    public Object getLabel(int vertex) {
        return labels[vertex];
    }

    public boolean isEdge(int source, int target) {
        return edges[source][target] >= 0;
    }

    public void removeEdge(int source, int target) {
        edges[source][target] = -1;
    }

    public void setLabel(int vertex, Object newLabel) {
        labels[vertex] = newLabel;
    }

    public int size( ) {
        return labels.length;
    }

    public static void main(String[] args) {
        Problem3 graph = new Problem3(4);
        graph.setLabel(0, "Byteville");
        graph.setLabel(1, "Bitburg");
        graph.setLabel(2, "Nulltown");
        graph.setLabel(3, "Binaria");
        graph.addEdge(0,1, 1.5);
        graph.addEdge(1,2, 2.2);
        graph.addEdge(2,3, 1.4);
        graph.addEdge(3,0, 3.9);
        int[] path1 = {1, 2, 3};
        graph.printTotalPath(path1);
        int[] path2 = {0, 2, 3};
        graph.printTotalPath(path2);
    }

}

3 7 0 6 2 5 1 2 8

Initial values... allowed: false false false false false false distance: Infinity Infinity Infinity Infinity 0.0 Infinity Executing loop... allowed: false false false false true false distance : Infinity Infinity 7.0 3.0 0.0 Infinity allowed: false false false true true false distance : Infinity Infinity 7.0 3.0 0.0 Infinity allowed: false false true true true false distance: Infinity Infinity 7.0 3.00.0 Infinity allowed: false false true true true false distance: Infinity Infinity 7.0 3.0 0.0 Infinity allowed: false false true true true false distance: Infinity Infinity 7.03.0 0.0 Infinity There is no path from 4 to0
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Dijkstra's shotest path code in java

import java.util.PriorityQueue;

import java.util.List;

import java.util.ArrayList;

import java.util.Collections;

public class DijkstraAlgo{

/* Dijkstra Algorithm

*

*

*/

public static void computePaths(Node source){

source.shortestDistance=0;

//implement a priority queue

PriorityQueue<Node> queue = new PriorityQueue<Node>();

queue.add(source);

while(!queue.isEmpty()){

Node u = queue.poll();

/*visit the adjacencies, starting from

the nearest node(smallest shortestDistance)*/

for(Edge e: u.adjacencies){

Node v = e.target;

double weight = e.weight;

//relax(u,v,weight)

double distanceFromU = u.shortestDistance+weight;

if(distanceFromU<v.shortestDistance){

/*remove v from queue for updating

the shortestDistance value*/

queue.remove(v);

v.shortestDistance = distanceFromU;

v.parent = u;

queue.add(v);

}

}

}

}

public static List<Node> getShortestPathTo(Node target){

//trace path from target to source

List<Node> path = new ArrayList<Node>();

for(Node node = target; node!=null; node = node.parent){

path.add(node);

}

//reverse the order such that it will be from source to target

Collections.reverse(path);

return path;

}

public static void main(String[] args){

//initialize the graph base on the Romania map

Node n1 = new Node("Arad");

Node n2 = new Node("Zerind");

Node n3 = new Node("Oradea");

Node n4 = new Node("Sibiu");

Node n5 = new Node("Fagaras");

Node n6 = new Node("Rimnicu Vilcea");

Node n7 = new Node("Pitesti");

Node n8 = new Node("Timisoara");

Node n9 = new Node("Lugoj");

Node n10 = new Node("Mehadia");

Node n11 = new Node("Drobeta");

Node n12 = new Node("Craiova");

Node n13 = new Node("Bucharest");

Node n14 = new Node("Giurgiu");

//initialize the edges

n1.adjacencies = new Edge[]{

new Edge(n2,75),

new Edge(n4,140),

new Edge(n8,118)

};

n2.adjacencies = new Edge[]{

new Edge(n1,75),

new Edge(n3,71)

};

n3.adjacencies = new Edge[]{

new Edge(n2,71),

new Edge(n4,151)

};

n4.adjacencies = new Edge[]{

new Edge(n1,140),

new Edge(n5,99),

new Edge(n3,151),

new Edge(n6,80),

};

n5.adjacencies = new Edge[]{

new Edge(n4,99),

new Edge(n13,211)

};

n6.adjacencies = new Edge[]{

new Edge(n4,80),

new Edge(n7,97),

new Edge(n12,146)

};

n7.adjacencies = new Edge[]{

new Edge(n6,97),

new Edge(n13,101),

new Edge(n12,138)

};

n8.adjacencies = new Edge[]{

new Edge(n1,118),

new Edge(n9,111)

};

n9.adjacencies = new Edge[]{

new Edge(n8,111),

new Edge(n10,70)

};

n10.adjacencies = new Edge[]{

new Edge(n9,70),

new Edge(n11,75)

};

n11.adjacencies = new Edge[]{

new Edge(n10,75),

new Edge(n12,120)

};

n12.adjacencies = new Edge[]{

new Edge(n11,120),

new Edge(n6,146),

new Edge(n7,138)

};

n13.adjacencies = new Edge[]{

new Edge(n7,101),

new Edge(n14,90),

new Edge(n5,211)

};

n14.adjacencies = new Edge[]{

new Edge(n13,90)

};

Node[] nodes = {n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14};

//compute paths

computePaths(n1);

//print shortest paths

/*

for(Node n: nodes){

System.out.println("Distance to " +

n + ": " + n.shortestDistance);

List<Node> path = getShortestPathTo(n);

System.out.println("Path: " + path);

}*/

List<Node> path = getShortestPathTo(n13);

System.out.println("Path: " + path);

}

}

//define Node

class Node implements Comparable<Node>{

public final String value;

public Edge[] adjacencies;

public double shortestDistance = Double.POSITIVE_INFINITY;

public Node parent;

public Node(String val){

value = val;

}

public String toString(){

return value;

}

public int compareTo(Node other){

return Double.compare(shortestDistance, other.shortestDistance);

}

}

//define Edge

class Edge{

public final Node target;

public final double weight;

public Edge(Node targetNode, double weightVal){

target = targetNode;

weight = weightVal;

}

}
Sign up for free

Add a comment
Know the answer?
Add Answer to:
Please follow all the instructions and do all the parts (a-d)! Create a Java program which implem...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

  • Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void...

    Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void main(String[] args) { int currentVertex, userChoice; Scanner input = new Scanner(System.in); // create graph using your WeightedGraph based on author's Graph WeightedGraph myGraph = new WeightedGraph(4); // add labels myGraph.setLabel(0,"Spot zero"); myGraph.setLabel(1,"Spot one"); myGraph.setLabel(2,"Spot two"); myGraph.setLabel(3,"Spot three"); // Add each edge (this directed Graph has 5 edges, // so we add 5 edges) myGraph.addEdge(0,2,9); myGraph.addEdge(1,0,7); myGraph.addEdge(2,3,12); myGraph.addEdge(3,0,15); myGraph.addEdge(3,1,6); // let's pretend we are on...

  • Please try your best to complete this 11 methods under. I have provided the UndirectedGraph class...

    Please try your best to complete this 11 methods under. I have provided the UndirectedGraph class with the single instance data variable. Do not add any additional instance data variables. Do not modify any other classes provided. In addition to writing the 8 required methods of the interface and the constructor, you will also write methods for the two traversals and an isConnected method. import java.util.Queue; public class UndirectedGraph<T> implements BasicGraphInterface <T> {       private DirectedGraph digraph;      ...

  • You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a...

    You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a graph stored as an adjacency list. The AdjacencyList class inherits from the Graph class shown below. class Graph { private: vector _distances; vector _previous; public: Graph() { } virtual int vertices() const = 0; virtual int edges() const = 0; virtual int distance(int) const = 0; virtual void bfs(int) const = 0; virtual void dfs(int) const = 0; virtual void display() const = 0;...

  • JAVA QUESTION!!! please help! The following codes are a Maze program. There are TWO traversable paths...

    JAVA QUESTION!!! please help! The following codes are a Maze program. There are TWO traversable paths possible in this maze. The program uses recursion. Can someone please explain to me why the program will pick one path if multiple traversable paths are available? Why does the program choose one path over a different path? (I believe it has something to do with the recursion terminating when a solution is found but I'm not sure.) Thank you!!!! The codes: public class...

  • Create a program via Java that has atleast 8 characters long, one upper case, and one...

    Create a program via Java that has atleast 8 characters long, one upper case, and one lower case, and one digit. here is my code:     public static void main(String[] args)     {         //variables defined         String passwords;         char password =0;                 //settings up password condition to false         boolean passwordcondition= false;         boolean size=false;         boolean digit=false;         boolean upper=false;         boolean lower=false;         //inputting a scanner into the system         Scanner keyboard = new Scanner(System.in);...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • Please help to make the program working. Can not compile. import java.io.*; import java .util.*; public...

    Please help to make the program working. Can not compile. import java.io.*; import java .util.*; public class Puzzlee {                 static int NN = 9; // Grid Size // sample input static int myGrid[][] = {                                                                                                                                                                                                                                                                                {0,0,0,1,0,5,0,6,8},                                                                                                                 {0,0,0,0,0,0,7,0,1},                                                                                                                 {9,0,1,0,0,0,0,3,0},                                                                                                                 {0,0,7,0,2,6,0,0,0},                                                                                                                 {5,0,0,0,0,0,0,0,3},                                                                                                                 {0,0,0,8,7,0,4,0,0},                                                                                                                 {0,3,0,0,0,0,8,0,5},                                                                                                                 {1,0,5,0,0,0,0,0,0},                                                                                                                 {7,9,0,4,0,1,0,0,0}                                                                                                 };    static class myCell {                 int myRow, myColumn;                 public myCell(int myRow, int myColumn)                 {                                 super();                                ...

  • Consider the java Graph class below which represents an undirected graph in an adjacency list. How...

    Consider the java Graph class below which represents an undirected graph in an adjacency list. How would you add a method to delete an edge from the graph? // Exercise 4.1.3 (Solution published at http://algs4.cs.princeton.edu/) package algs41; import stdlib.*; import algs13.Bag; /** * The <code>Graph</code> class represents an undirected graph of vertices * named 0 through V-1. * It supports the following operations: add an edge to the graph, * iterate over all of the neighbors adjacent to a vertex....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT