Question
Java coding create a map of a city subway system using a Graph data structure. The Metro Station Map that you'll use for this is
Java coding
create a map of a city subway system using a Graph data structure. The Metro Station Map that you'll use for this is here:
Enter all the information from the Metro Station Map into your Graph following these guidelines:
1) Delete all the vertices and edges that were made in the main method of the example code (start with a blank Graph)(Example code is provided at the end)
2) Add the network of stations and the travel times (weights) to the graph. Modify the addEdge() method to make the graph undirected (when you add an edge, also add the reverse connection)
3) Using the data in your graph, determine the travel time from station 6 to station 2 when taking the following path: 6,3,1,2
For part 3, DO NOT just sum up the travel times from the Map that was provided. Your code should use the graph you created and follow the path from station to station and sum up the travel times.
import java.util.*;
class Graph
{
// Edge object that is stored for each connection to another node
class Edge
{
int v,w;
public Edge(int v,int w)
{
this.v=v; this.w=w;
}
@Override
public String toString()
{
return "("+v+","+w+")";
}
}
// An array of lists of Edge objects
List
// Parameterized constructor
public Graph(int n)
{
G = new LinkedList[n];
// For each node in the graph, initialize an empty
adjacency list
for(int i=0; i G[i]=new LinkedList } // Check if node U is connected to node V boolean isConnected(int u,int v) { // Check each edge for this node to see if it connects to node V for(Edge i: G[u]) if(i.v==v) return true; return false; } // For node U, add a new connection to node V, with weight W void addEdge(int u,int v,int w) { G[u].add(new Edge(v,w)); } // Override the java default toString() method so we can print // our Graph in the format we want @Override public String toString() { String result=""; for(int i=0;i result+=i+"=>"+G[i]+" "; return result; } } public class GraphExample { public static void main(String[] args) { Graph g=new Graph(10); g.addEdge(0, 2, 10); g.addEdge(0, 5, 15); g.addEdge(2, 5, 10); g.addEdge(9, 3, 16); System.out.println(g); System.out.println(g.isConnected(9,3)); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started