SlideShare a Scribd company logo
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public Vertex(String placeName, boolean hasChargingStataion) {
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
public void setVisited(boolean b) {
}
public Edge[] getAdjacentEdges() {
return null;
}
public boolean isVisited() {
return false;
}
public boolean isChargingStationAvailable() {
return false;
}
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Edge(Vertex vtx1, Vertex vtx2, int length2) {
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
public Vertex getEnd() {
return null;
}
}
//A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map and determine if two places are connnected by a path with
charging stations:");
System.err.println(" java RoadMap -c <MapFile> <StartVertexIndex> <EndVertexIndex>");
System.err.println(" - Load a map and determine the mininmum number of assistance cars
required:");
System.err.println(" java RoadMap -a <MapFile>");
}
public static void main(String[] args) throws Exception {
if (args.length == 2 && args[0].equals("-i")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Error in reading map file");
System.exit(-1);
}
System.out.println();
System.out.println("Read road map from " + args[1] + ":");
map.printMap();
System.out.println();
}
else if (args.length == 2 && args[0].equals("-a")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Error in reading map file");
System.exit(-1);
}
System.out.println();
System.out.println("Read road map from " + args[1] + ":");
map.printMap();
int n = map.minNumAssistanceCars();
System.out.println();
System.out.println("The map requires at least " + n + " assistance car(s)");
System.out.println();
}
else if (args.length == 4 && args[0].equals("-c")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Error in reading map file");
System.exit(-1);
}
System.out.println();
System.out.println("Read road map from " + args[1] + ":");
map.printMap();
int startVertexIdx = -1, endVertexIdx = -1;
try {
startVertexIdx = Integer.parseInt(args[2]);
endVertexIdx = Integer.parseInt(args[3]);
} catch (NumberFormatException e) {
System.err.println("Error: start vertex and end vertex must be specified using their indices");
System.exit(-1);
}
if (startVertexIdx < 0 || startVertexIdx >= map.numPlaces()) {
System.err.println("Error: invalid index for start vertex");
System.exit(-1);
}
if (endVertexIdx < 0 || endVertexIdx >= map.numPlaces()) {
System.err.println("Error: invalid index for end vertex");
System.exit(-1);
}
Vertex startVertex = map.getPlace(startVertexIdx);
Vertex endVertex = map.getPlace(endVertexIdx);
if (!map.isConnectedWithChargingStations(startVertex, endVertex)) {
System.out.println();
System.out.println("There is no path connecting " + map.getPlace(startVertexIdx).getName() + "
and "
+ map.getPlace(endVertexIdx).getName() + " with charging stations");
} else {
System.out.println();
System.out.println("There is at least one path connecting " +
map.getPlace(startVertexIdx).getName() + " and "
+ map.getPlace(endVertexIdx).getName() + " with charging stations");
}
System.out.println();
} else {
printCommandError();
System.exit(-1);
}
}
public void loadMap(String filename) {
File file = new File(filename);
places.clear();
roads.clear();
try {
Scanner sc = new Scanner(file);
//Read the first line: number of vertices and number of edges
int numVertices = sc.nextInt();
int numEdges = sc.nextInt();
for (int i = 0; i < numVertices; ++i) {
// Read the vertex name and its charing station flag
String placeName = sc.next();
int charginStationFlag = sc.nextInt();
boolean hasChargingStataion = (charginStationFlag == 1);
// Create a new vertex using the information above and add it to places
Vertex newVertex = new Vertex(placeName, hasChargingStataion, i);
places.add(newVertex);
}
for (int j = 0; j < numEdges; ++j) {
// Read the edge length and the indices for its two vertices
int vtxIndex1 = sc.nextInt();
int vtxIndex2 = sc.nextInt();
int length = sc.nextInt();
Vertex vtx1 = places.get(vtxIndex1);
Vertex vtx2 = places.get(vtxIndex2);
Edge newEdge = new Edge(length, vtx1, vtx2);
Edge reverseEdge = new Edge(length, vtx2, vtx1);
vtx1.addIncidentRoad(newEdge);
vtx2.addIncidentRoad(reverseEdge);
roads.add(newEdge);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
places.clear();
roads.clear();
}
}
the question is :
//Check if two vertices are connected by a path with charging stations on each itermediate vertex.
//Return true if such a path exists; return false otherwise.
//The worst-case time complexity of your algorithm should be no worse than O(v + e),
//where v and e are the number of vertices and the number of edges in the graph.
starting with
public boolean isConnectedWithChargingStations(Vertex startVertex, Vertex endVertex) {
if (startVertex.getIndex() == endVertex.getIndex()) {
return true;
}

More Related Content

DOCX
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
DOCX
In Arevalo- Aravind- Ayuso and Roca's (2013) article- we learn that th.docx
DOCX
In a Word document- you will need to list and define all key terms wit.docx
DOCX
In a survey of 2918 adults- 1477 say they have started paying bills on.docx
DOCX
In a population of yellow mushrooms- a mutation resulted in a new purp (1).docx
DOCX
In a particular hospital- 5 newborn babies were delivered yesterday- H.docx
DOCX
In a paper written by Bendey Coliege econonists Patricia M- Flynn and.docx
DOCX
In a given population of Drosophila- curly wings (c) is recessive to t.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
In Arevalo- Aravind- Ayuso and Roca's (2013) article- we learn that th.docx
In a Word document- you will need to list and define all key terms wit.docx
In a survey of 2918 adults- 1477 say they have started paying bills on.docx
In a population of yellow mushrooms- a mutation resulted in a new purp (1).docx
In a particular hospital- 5 newborn babies were delivered yesterday- H.docx
In a paper written by Bendey Coliege econonists Patricia M- Flynn and.docx
In a given population of Drosophila- curly wings (c) is recessive to t.docx

More from Blake0FxCampbelld (20)

DOCX
In a large population- 51- of the people have been vaccinated- If 4 pe.docx
DOCX
In a geographic isolate- a small population has been studied for a gen.docx
DOCX
In a democracy- politicians may be shortsighted because they want to w.docx
DOCX
In a certain city- the daily consumption of water (in millions of lite.docx
DOCX
In a certain geographic location 15- of individuals have disease A- 15.docx
DOCX
In 2014- the General Social Survey incuded a question about the role o.docx
DOCX
In 1993- when Fischer began his tenure at Kodak- the film industry was.docx
DOCX
In search engines analyzes the sequences of search queries to identif.docx
DOCX
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
DOCX
Implement the Plates class buildMap function so that it populates the.docx
DOCX
Implementing AES- Native Instructions (AES-NI) is faster than other im.docx
DOCX
Implement these classes and a interface in 3 Java programs- Class 1- T.docx
DOCX
Implement the following in my java program which is written under the.docx
DOCX
Immature neutrophils released from the bone marrow in response to infe.docx
DOCX
Imagine you have a gram negative pathogen that uses many different sec.docx
DOCX
If the probability density function of a continuous random variable X.docx
DOCX
Imagine I conduct a study in which I test the effectiveness of music l.docx
DOCX
Imagine that a mutant strain of Drosophila undergoes crossing over at.docx
DOCX
If the Italian Lira is trading at $1-44- what is the Indirect quote of.docx
DOCX
iill (Click the icon to view the dats) Requirements a- FIFO b- Woghtod.docx
In a large population- 51- of the people have been vaccinated- If 4 pe.docx
In a geographic isolate- a small population has been studied for a gen.docx
In a democracy- politicians may be shortsighted because they want to w.docx
In a certain city- the daily consumption of water (in millions of lite.docx
In a certain geographic location 15- of individuals have disease A- 15.docx
In 2014- the General Social Survey incuded a question about the role o.docx
In 1993- when Fischer began his tenure at Kodak- the film industry was.docx
In search engines analyzes the sequences of search queries to identif.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
Implement the Plates class buildMap function so that it populates the.docx
Implementing AES- Native Instructions (AES-NI) is faster than other im.docx
Implement these classes and a interface in 3 Java programs- Class 1- T.docx
Implement the following in my java program which is written under the.docx
Immature neutrophils released from the bone marrow in response to infe.docx
Imagine you have a gram negative pathogen that uses many different sec.docx
If the probability density function of a continuous random variable X.docx
Imagine I conduct a study in which I test the effectiveness of music l.docx
Imagine that a mutant strain of Drosophila undergoes crossing over at.docx
If the Italian Lira is trading at $1-44- what is the Indirect quote of.docx
iill (Click the icon to view the dats) Requirements a- FIFO b- Woghtod.docx
Ad

Recently uploaded (20)

PPTX
master seminar digital applications in india
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Classroom Observation Tools for Teachers
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharma ospi slides which help in ospi learning
PDF
Pre independence Education in Inndia.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
master seminar digital applications in india
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Classroom Observation Tools for Teachers
O7-L3 Supply Chain Operations - ICLT Program
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Supply Chain Operations Speaking Notes -ICLT Program
human mycosis Human fungal infections are called human mycosis..pptx
Renaissance Architecture: A Journey from Faith to Humanism
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharma ospi slides which help in ospi learning
Pre independence Education in Inndia.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPH.pptx obstetrics and gynecology in nursing
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Ad

import java-util--- import java-io--- class Vertex { -- Constructo.docx

  • 1. import java.util.*; import java.io.*; class Vertex { // Constructor: set name, chargingStation and index according to given values, // initilaize incidentRoads as empty array public Vertex(String placeName, boolean chargingStationAvailable, int idx) { name = placeName; incidentRoads = new ArrayList<Edge>(); index = idx; chargingStation = chargingStationAvailable; } public Vertex(String placeName, boolean hasChargingStataion) { } public String getName() { return name; } public boolean hasChargingStation() { return chargingStation; } public ArrayList<Edge> getIncidentRoads() { return incidentRoads; } // Add a road to the array incidentRoads
  • 2. public void addIncidentRoad(Edge road) { incidentRoads.add(road); } public int getIndex() { return index; } private String name; // Name of the place ArrayList<Edge> incidentRoads; // Incident edges private boolean chargingStation; // Availability of charging station private int index; // Index of this vertex in the vertex array of the map public void setVisited(boolean b) { } public Edge[] getAdjacentEdges() { return null; } public boolean isVisited() { return false; } public boolean isChargingStationAvailable() { return false; } } class Edge {
  • 3. public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) { length = roadLength; incidentPlaces = new Vertex[] { firstPlace, secondPlace }; } public Edge(Vertex vtx1, Vertex vtx2, int length2) { } public Vertex getFirstVertex() { return incidentPlaces[0]; } public Vertex getSecondVertex() { return incidentPlaces[1]; } public int getLength() { return length; } private int length; private Vertex[] incidentPlaces; public Vertex getEnd() { return null; } } //A class that represents a sparse matrix public class RoadMap {
  • 4. // Default constructor public RoadMap() { places = new ArrayList<Vertex>(); roads = new ArrayList<Edge>(); } // Auxiliary function that prints out the command syntax public static void printCommandError() { System.err.println("ERROR: use one of the following commands"); System.err.println(" - Load a map and print information:"); System.err.println(" java RoadMap -i <MapFile>"); System.err.println(" - Load a map and determine if two places are connnected by a path with charging stations:"); System.err.println(" java RoadMap -c <MapFile> <StartVertexIndex> <EndVertexIndex>"); System.err.println(" - Load a map and determine the mininmum number of assistance cars required:"); System.err.println(" java RoadMap -a <MapFile>"); } public static void main(String[] args) throws Exception { if (args.length == 2 && args[0].equals("-i")) { RoadMap map = new RoadMap(); try { map.loadMap(args[1]); } catch (Exception e) { System.err.println("Error in reading map file");
  • 5. System.exit(-1); } System.out.println(); System.out.println("Read road map from " + args[1] + ":"); map.printMap(); System.out.println(); } else if (args.length == 2 && args[0].equals("-a")) { RoadMap map = new RoadMap(); try { map.loadMap(args[1]); } catch (Exception e) { System.err.println("Error in reading map file"); System.exit(-1); } System.out.println(); System.out.println("Read road map from " + args[1] + ":"); map.printMap(); int n = map.minNumAssistanceCars(); System.out.println(); System.out.println("The map requires at least " + n + " assistance car(s)"); System.out.println(); }
  • 6. else if (args.length == 4 && args[0].equals("-c")) { RoadMap map = new RoadMap(); try { map.loadMap(args[1]); } catch (Exception e) { System.err.println("Error in reading map file"); System.exit(-1); } System.out.println(); System.out.println("Read road map from " + args[1] + ":"); map.printMap(); int startVertexIdx = -1, endVertexIdx = -1; try { startVertexIdx = Integer.parseInt(args[2]); endVertexIdx = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Error: start vertex and end vertex must be specified using their indices"); System.exit(-1); } if (startVertexIdx < 0 || startVertexIdx >= map.numPlaces()) { System.err.println("Error: invalid index for start vertex"); System.exit(-1); }
  • 7. if (endVertexIdx < 0 || endVertexIdx >= map.numPlaces()) { System.err.println("Error: invalid index for end vertex"); System.exit(-1); } Vertex startVertex = map.getPlace(startVertexIdx); Vertex endVertex = map.getPlace(endVertexIdx); if (!map.isConnectedWithChargingStations(startVertex, endVertex)) { System.out.println(); System.out.println("There is no path connecting " + map.getPlace(startVertexIdx).getName() + " and " + map.getPlace(endVertexIdx).getName() + " with charging stations"); } else { System.out.println(); System.out.println("There is at least one path connecting " + map.getPlace(startVertexIdx).getName() + " and " + map.getPlace(endVertexIdx).getName() + " with charging stations"); } System.out.println(); } else { printCommandError(); System.exit(-1); } } public void loadMap(String filename) {
  • 8. File file = new File(filename); places.clear(); roads.clear(); try { Scanner sc = new Scanner(file); //Read the first line: number of vertices and number of edges int numVertices = sc.nextInt(); int numEdges = sc.nextInt(); for (int i = 0; i < numVertices; ++i) { // Read the vertex name and its charing station flag String placeName = sc.next(); int charginStationFlag = sc.nextInt(); boolean hasChargingStataion = (charginStationFlag == 1); // Create a new vertex using the information above and add it to places Vertex newVertex = new Vertex(placeName, hasChargingStataion, i); places.add(newVertex); } for (int j = 0; j < numEdges; ++j) { // Read the edge length and the indices for its two vertices int vtxIndex1 = sc.nextInt(); int vtxIndex2 = sc.nextInt(); int length = sc.nextInt(); Vertex vtx1 = places.get(vtxIndex1);
  • 9. Vertex vtx2 = places.get(vtxIndex2); Edge newEdge = new Edge(length, vtx1, vtx2); Edge reverseEdge = new Edge(length, vtx2, vtx1); vtx1.addIncidentRoad(newEdge); vtx2.addIncidentRoad(reverseEdge); roads.add(newEdge); } sc.close(); } catch (Exception e) { e.printStackTrace(); places.clear(); roads.clear(); } } the question is : //Check if two vertices are connected by a path with charging stations on each itermediate vertex. //Return true if such a path exists; return false otherwise. //The worst-case time complexity of your algorithm should be no worse than O(v + e), //where v and e are the number of vertices and the number of edges in the graph. starting with public boolean isConnectedWithChargingStations(Vertex startVertex, Vertex endVertex) { if (startVertex.getIndex() == endVertex.getIndex()) { return true;
  • 10. }