Question

Using java can someone help me create a program using the following instructions.

4. (70 points) Implement Dijkstras algorithm for computing a shortest path from a designated vertex (A) to a designated vertex (B) in a directed graph. Your implementation should use a minimum heap as a supporting data structure. Please follow the instructions below.

Input file:

10
A J 18
A H 79
A I 81
J G 24
J F 76
G F 2
G H 50
F E 4
E D 2
D H 20
H C 50
I D 6
I C 97
I J 27
C B 22

Solution File:

142
A J G F E D H C B

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE TO COPY:

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Scanner;

import java.util.List;

import java.util.PriorityQueue;

//edge class to hold the edge source, destinationa and the weight of the edge

class GraphEdge{

private char from;

private char to;

private int weight;

public GraphEdge(char from, char to, int weight)

{

this.from=from;

this.to=to;

this.weight=weight;

}

public char getFrom()

{

return from;

}

public char getTo()

{

return to;

}

public int getWeight()

{

return weight;

}

public String toString()

{

return "From: "+from+"\tTo: "+to+"\tWeight: "+weight;

}

}

public class DijkstraAlgorithmTest {

public static void main(String[] args) throws FileNotFoundException {

File file=new File("dijkstraFile.txt");//input file

Scanner obj=new Scanner(file);//scanner object to read data from file

char source='A';//source vertex

char destination='B';//destination vertex

ArrayList<GraphEdge> edges=new ArrayList<GraphEdge>();//list to hold all edges

HashSet<Character> uniqueVertices=new HashSet<Character>();//all unique vertices in map

ArrayList<Character> allVertices=new ArrayList<Character>();//list to hold all vertices

int numberOfVertices=Integer.parseInt(obj.nextLine());

while(obj.hasNextLine())

{//while input file has lines left

String line=obj.nextLine();

String vertex[]=line.split(" ");//split the line into source vertex, destination vertex and the weight

GraphEdge edge=new GraphEdge(vertex[0].charAt(0), vertex[1].charAt(0), Integer.parseInt(vertex[2]));//create a new graphedge object from line data

edges.add(edge);

if(!uniqueVertices.contains(vertex[0].charAt(0)))

{//if vertex not present in unique vertices map, add it in map and arraylist

uniqueVertices.add(vertex[0].charAt(0));

allVertices.add(vertex[0].charAt(0));

}

if(!uniqueVertices.contains(vertex[1].charAt(0)))

{//if vertex not present in unique vertices map, add it in map and arraylist

uniqueVertices.add(vertex[1].charAt(0));

allVertices.add(vertex[1].charAt(0));

}

}

HashMap<Character, Integer> distance=new HashMap<Character, Integer>();

for(Character ch: allVertices)

{

distance.put(ch, Integer.MAX_VALUE);//add all vertices to distance map with initial distance as infinite i.e Integer.MAX_VALUE

}

distance.put(source, 0);//source distance is 0, update in distance map

//comparator to arrange the vertices in the priority queue in min heap fashion

Comparator<Character> cmp=new Comparator<Character>()

{

public int compare(Character a, Character b)

{

if(distance.get(a)<distance.get(b))

return -1;

else if(distance.get(a)==distance.get(b))

return 0;

else

return 1;

}

};

//create a priority queue

PriorityQueue<Character> pq=new PriorityQueue<Character>(cmp);//priority queue / min heap to arrange vertices in min heap fashion

for(Character ch: allVertices)

pq.add(ch);//add all the vertices to pq

String path="";//hold the final path from a to b

while(!pq.isEmpty())

{//while there are elements in the pq

char ch=pq.remove();//get the vertex

path+=ch;//append the vertex to path

if(ch==destination)//if reached destination

break;//loop out

List<GraphEdge> outVertex=getAllOutgoingEdges(edges, ch);

for(GraphEdge edge:outVertex)

{//for each egde in the outVertex list

if(pq.contains(edge.getTo()))

{//if the destination vertex in the edge is present in the pq

if(distance.get(ch)+edge.getWeight()<distance.get(edge.getTo()))

{//if new distance is less than the old distance

distance.put(edge.getTo(), distance.get(ch)+edge.getWeight());//put new distance

}

//the below 2 lines are executed to update the priority queue after change to distance

pq.remove(edge.getTo());//remove destination vertex of edge to pq

pq.add(edge.getTo());//add destination vertex of edge to pq

}

}

}

// solution file

File output=new File("DijkstraSolution.txt");

PrintWriter pw=new PrintWriter(output);

pw.println(distance.get(destination));//print the minuimum distance to destination to file

pw.println(path);//print the path to file

//print a successful message to the console

System.out.println("Successful!");

pw.flush();//flush the output to file

pw.close();//close pw

obj.close();//close obj

}

//get all the outgoing edges in a list from the source vetrtex

public static List<GraphEdge> getAllOutgoingEdges(ArrayList<GraphEdge> list, char source)

{

List<GraphEdge> result=new ArrayList<GraphEdge>();

for(GraphEdge edge: list)

{

if(edge.getFrom()==source)

result.add(edge);

}

return result;

}

}

PROGRAM SCREENSHOTS:

my java_programs - Chegg QA/c/May_2018/DijkstraAlgorithm Test.java - Eclipse File Edit Source Refactor Navigate Search Projecmy java_programs - Chegg QA/c/May_2018/DijkstraAlgorithm Test.java - Eclipse File Edit Source Refactor Navigate Search Projecmy java_programs - Chegg QA/c/May_2018/DijkstraAlgorithm Test.java - Eclipse File Edit Source Refactor Navigate Search Projecmy java_programs - Chegg QA/c/May_2018/DijkstraAlgorithm Test.java - Eclipse File Edit Source Refactor Navigate Search Projecmy java_programs - Chegg QA/c/May_2018/DijkstraAlgorithm Test.java - Eclipse File Edit Source Refactor Navigate Search Projec


INPUT FILE:

dijkstraFile-Notepad File Edit Format View Help he 2 ^ do ENG 16:25


OUTPUT FILE:

DijkstraSolution - Notepad File Edit Format View Help 142 AJGFEDHICB ^七.irido ENG 16:25 모


CONSOLE OUTPUT:

myjava-programs-Eclipse File Edit Navigate Search Project Run Window Help Quick Access 曰Console D UltimateFri.. D TreeTest ja

Add a comment
Know the answer?
Add Answer to:
Using java can someone help me create a program using the following instructions. Input file: 10...
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
  • Hi I'm stuck with this homework question and hope you can help me. 9. In the...

    Hi I'm stuck with this homework question and hope you can help me. 9. In the graph below (A) Determine the shortest path from a to ALL other nodes using Dijkstra's Shortest Path Algorithm. The answers must be in the following form: For each node, give the shortest path from a to that node (that is, list the nodes in the path) Also for each path give the length of the path. (B) ON THIS SHEET OF PAPER SHOWING A...

  • Please follow all the instructions and do all the parts (a-d)! Create a Java program which implem...

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

  • Shortest Path (DAG) Students, In this coding assignment, you will be asked to write Java code...

    Shortest Path (DAG) Students, In this coding assignment, you will be asked to write Java code to read a text file (input.txt) of a graph represented as an adjacency list. Example: A, 7, B, 9, C B, 1, C C, 8, E, 2, F D, 1, E, 3, G E, 3, G F, 3, D, -3, H H, 6, G K, 3, H, -1, F The graph represented by the adjacency list above looks like this: The graph is a...

  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given. Write a driver program, which reads input file mediumG.txt as an undirected graph and runs the depth-first search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to ‘v’: list of all the vertices traversed to...

  • 5. If we apply binary dilation to the same large object twice using the same small...

    5. If we apply binary dilation to the same large object twice using the same small structuring element, the effect, if any, of the second dilation on the object is that the object: (a) is unchanged (b) is completely removed (c) becomes larger (d) becomes smaller (e) does not change 6. Which of the following is/are true? (a) Dijkstra's algorithm can be used to find shortest paths in a network (b) Dijkstra's algorithm is a method to find straight lines...

  • Run the Dijkstra’s algorithm on the directed graph of the following figure 24.6, using vertex t...

    Run the Dijkstra’s algorithm on the directed graph of the following figure 24.6, using vertex t as the source. In the style of Figure 24.6, show the d and ? values and the vertices in set S after each iteration of the while loop. 1 8 10 I 10 14 4 6 4 6 2 3 2 3 4 6 5 5 2 (a) (c) 1 10 13 4 6 (d) (e) Figure 24.6 The execution of Dijkstra's algorithm. The...

  • Using c 3 File Input & Data Processing Reading data from a file is often done in order to pro...

    using c 3 File Input & Data Processing Reading data from a file is often done in order to process and aggregate it to get ad- ditional results. In this activity you will read in data from a file containing win/loss data from the 2011 Major League Baseball season. Specifically, the file data/mlb_nl_2011.txt contains data about each National League team. Each line contains a team name fol- lowed by the number of wins and number of losses during the 2011...

  • Give 10 cities located within 1,000 miles (left to right) by 1,000 miles (bottom to top)...

    Give 10 cities located within 1,000 miles (left to right) by 1,000 miles (bottom to top) region, calculate the shortest traveling path from the traveling salesman problem. The 10 cities are A, B, C, D, E, F, G, H, I, and J. Locations of 10 cities are A (X: 100, Y: 300) B (X: 200, Y: 130) C (X: 300, Y: 500) D (X: 500, Y: 390) E (X: 700, Y: 300) F (X: 900, Y: 600) G (X: 800,...

  • This is a Python Program Write a program that encrypts letters based on the following key....

    This is a Python Program Write a program that encrypts letters based on the following key. Original letter to encrypted letter A M B L C K D J E I F H G G H F I E J D K C L B M A N Z O Y P X Q W R V S U T T U S V R W Q X P Y O Z N Write the output to a file

  • Given the following test scores on exam #1 for INEN 370 during the summer 2017: Due...

    Given the following test scores on exam #1 for INEN 370 during the summer 2017: Due Name Date: Tuesday, January 29, 2019 ISEN 370-Engineering Statistics Assignment # 2 Homework I.(60) Given the following test scores on Exam # 1 for INEN 370 during the Summer 2017 93 77 67 72 528366 84 59 63 75 97 84 73 814261 51 91 87 34 54 7 47 79 706557 90 83 58 69 82 76 716038 81 74 69 68 76...

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