You are on page 1of 19

MAPGRAPH.

java

/**

*/

package roadgraph;

import java.util.Collection;

import java.util.HashMap;

import java.util.HashSet;

import java.util.LinkedList;

import java.util.List;

import java.util.PriorityQueue;

import java.util.Queue;

import java.util.Set;

import java.util.function.BiFunction;

import java.util.function.Consumer;

import geography.GeographicPoint;

import util.GraphLoader;

/**

* @author UCSD MOOC development team

* A class which represents a graph of geographic locations Nodes in the

* graph are intersections of multiple roads. Edges are the roads.

*/

public class MapGraph {


/*Manteniendo ambos nodos y arista para conocer

*la latitud y longitud de los caminos que contengan*/

private HashMap<GeographicPoint, MapNode> pointNodeMap;

private HashSet<MapEdge> edges;

/**

* Create a new empty MapGraph

*/

/*constructor de la clase, inicia los puntos del mapa y sus aristas.*/

public MapGraph() {

pointNodeMap = new HashMap<GeographicPoint, MapNode>();

edges = new HashSet<MapEdge>();

/**

* Get the number of vertices (road intersections) in the graph

* @return The number of vertices in the graph.

*/

public int getNumVertices() {

return pointNodeMap.values().size();

/**

* Get the number of road segments in the graph

* @return The number of edges in the graph.


*/

public int getNumEdges() {

return edges.size();

// For us in DEBUGGING. Print the Nodes in the graph

public void printNodes() {

System.out.println("****PRINTING NODES ********");

System.out.println("There are " + getNumVertices() + " Nodes: \n");

for (GeographicPoint pt : pointNodeMap.keySet()) {

MapNode n = pointNodeMap.get(pt);

System.out.println(n);

// For us in DEBUGGING. Print the Edges in the graph

public void printEdges() {

System.out.println("******PRINTING EDGES******");

System.out.println("There are " + getNumEdges() + " Edges:\n");

for (MapEdge e : edges) {

System.out.println(e);

/**

* Add a node corresponding to an intersection

* @param latitude
* The latitude of the location

* @param longitude

* The longitude of the location

*/

public void addVertex(double latitude, double longitude) {

GeographicPoint pt = new GeographicPoint(latitude, longitude);

this.addVertex(pt);

/**

* Add a node corresponding to an intersection at a Geographic Point

* @param location

* The location of the intersection

*/

public void addVertex(GeographicPoint location) {

MapNode n = pointNodeMap.get(location);

if (n == null) {

n = new MapNode(location);

pointNodeMap.put(location, n);

} else {

System.out.println("Warning: Node at location " + location + " already


exists in the graph.");

/**

* Add an edge representing a segment of a road. Precondition: The


* corresponding Nodes must have already been added to the graph.

* @param roadName

* The name of the road

* @param roadType

* The type of the road

*/

public void addEdge(double lat1, double lon1, double lat2, double lon2, String roadName,
String roadType) {

// Find the two Nodes associated with this edge.

GeographicPoint pt1 = new GeographicPoint(lat1, lon1);

GeographicPoint pt2 = new GeographicPoint(lat2, lon2);

MapNode n1 = pointNodeMap.get(pt1);

MapNode n2 = pointNodeMap.get(pt2);

// check nodes are valid

if (n1 == null)

throw new NullPointerException("addEdge: pt1:" + pt1 + "is not in graph");

if (n2 == null)

throw new NullPointerException("addEdge: pt2:" + pt2 + "is not in graph");

addEdge(n1, n2, roadName, roadType, MapEdge.DEFAULT_LENGTH);

public void addEdge(GeographicPoint pt1, GeographicPoint pt2, String roadName, String


roadType) {

MapNode n1 = pointNodeMap.get(pt1);
MapNode n2 = pointNodeMap.get(pt2);

// comprueba que los nodos son validos

if (n1 == null)

throw new NullPointerException("addEdge: pt1:" + pt1 + "is not in graph");

if (n2 == null)

throw new NullPointerException("addEdge: pt2:" + pt2 + "is not in graph");

addEdge(n1, n2, roadName, roadType, MapEdge.DEFAULT_LENGTH);

public void addEdge(GeographicPoint pt1, GeographicPoint pt2, String roadName, String


roadType, double length) {

MapNode n1 = pointNodeMap.get(pt1);

MapNode n2 = pointNodeMap.get(pt2);

// comprueba que el nodo sea valido

if (n1 == null)

throw new NullPointerException("addEdge: pt1:" + pt1 + "is not in graph");

if (n2 == null)

throw new NullPointerException("addEdge: pt2:" + pt2 + "is not in graph");

addEdge(n1, n2, roadName, roadType, length);

/** Given a point, return if there is a corresponding MapNode **/

public boolean isNode(GeographicPoint point) {

return pointNodeMap.containsKey(point);

}
// agrega una arista cuando ya conozcas los nos involucrados con la arista

private void addEdge(MapNode n1, MapNode n2, String roadName, String roadType,
double length) {

MapEdge edge = new MapEdge(roadName, roadType, n1, n2, length);

edges.add(edge);

n1.addEdge(edge);

/** Returns the nodes in terms of their geographic locations */

public Collection<GeographicPoint> getVertices() {

return pointNodeMap.keySet();

// obtener un conjunto de vecinos del mapa de nodos

private Set<MapNode> getNeighbors(MapNode node) {

return node.getNeighbors();

public List<GeographicPoint> bfs(GeographicPoint start, GeographicPoint goal) {

// Dummy variable for calling the search algorithms

Consumer<GeographicPoint> temp = (x) -> {

};

return bfs(start, goal, temp);

/**

* Find the path from start to goal using Breadth First Search

*
* @param start

* The starting location

* @param goal

* The goal location

* @return The list of intersections that form the shortest path from start

* to goal (including both start and goal).

*/

public List<GeographicPoint> bfs(GeographicPoint start, GeographicPoint goal,

Consumer<GeographicPoint> nodeSearched) {

if (!arePreconditionsFulfilled(start, goal)) {

return null;

MapNode startNode = pointNodeMap.get(start);

MapNode endNode = pointNodeMap.get(goal);

// configurando el inicio de BFS

HashMap<MapNode, MapNode> parentMap = new HashMap<MapNode,


MapNode>();

Queue<MapNode> toExplore = new LinkedList<MapNode>();

HashSet<MapNode> visited = new HashSet<MapNode>();

toExplore.add(startNode);

MapNode next = null;

while (!toExplore.isEmpty()) {

next = toExplore.remove();

// vista para visualizacion


nodeSearched.accept(next.getLocation());

if (next.equals(endNode))

break;

for (MapNode neighbor : getNeighbors(next)) {

if (!visited.contains(neighbor)) {

visited.add(neighbor);

parentMap.put(neighbor, next);

toExplore.add(neighbor);

// reconstruye la ruta primaria

return reconstructPath(parentMap, startNode, endNode, next.equals(endNode));

private boolean arePreconditionsFulfilled(GeographicPoint start, GeographicPoint goal) {

if (start == null || goal == null) {

throw new NullPointerException("Cannot find route from or to null


node");

if (pointNodeMap.get(start) == null) {

System.err.println("Start node " + start + " does not exist");

return false;

if (pointNodeMap.get(goal) == null) {

System.err.println("End node " + goal + " does not exist");


return false;

return true;

private List<GeographicPoint> reconstructPath(HashMap<MapNode, MapNode>


parentMap, MapNode start, MapNode goal,

boolean pathFound) {

if (!pathFound) {

System.out.println("No path found from " + start + " to " + goal);

return null;

LinkedList<GeographicPoint> path = new LinkedList<GeographicPoint>();

MapNode current = goal;

while (!current.equals(start)) {

path.addFirst(current.getLocation());

current = parentMap.get(current);

// agrega inicio.

path.addFirst(start.getLocation());

return path;

/** Find the path from start to goal using Dijkstra's algorithm

* @param start The starting location

* @param goal The goal location


* @return The list of intersections that form the shortest path from

* start to goal (including both start and goal).

*/

public List<GeographicPoint> dijkstra(GeographicPoint start, GeographicPoint goal) {

// Dummy variable for calling the search algorithms

// You do not need to change this method.

Consumer<GeographicPoint> temp = (x) -> {};

return dijkstra(start, goal, temp);

/** Find the path from start to goal using Dijkstra's algorithm

* @param start The starting location

* @param goal The goal location

* @param nodeSearched A hook for visualization. See assignment instructions for how to
use it.

* @return The list of intersections that form the shortest path from

* start to goal (including both start and goal).

*/

public List<GeographicPoint> dijkstra(GeographicPoint start,

GeographicPoint
goal, Consumer<GeographicPoint> nodeSearched)

// TODO: Implement this method in WEEK 3

// Hook for visualization. See writeup.

//nodeSearched.accept(next.getLocation());

return null;

}
/**

* Find the path from start to goal using A-Star search

* @param start

* The starting location

* @param goal

* The goal location

* @return The list of intersections that form the shortest path from start

* to goal (including both start and goal).

*/

public List<GeographicPoint> aStarSearch(GeographicPoint start, GeographicPoint goal) {

// Dummy variable for calling the search algorithms

Consumer<GeographicPoint> temp = (x) -> {

};

return aStarSearch(start, goal, temp);

/**

* Find the path from start to goal using A-Star search

* @param start

* The starting location

* @param goal

* The goal location

* @param nodeSearched

* A hook for visualization. See assignment instructions for how

* to use it.

* @return The list of intersections that form the shortest path from start

* to goal (including both start and goal).


*/

public List<GeographicPoint> aStarSearch(GeographicPoint start, GeographicPoint goal,

Consumer<GeographicPoint> nodeSearched) {

return null;

// main method for testing

public static void main(String[] args) {

/*

* Basic testing System.out.print("Making a new map..."); MapGraph

* theMap = new MapGraph(); System.out.print(

* "DONE. \nLoading the map...");

* GraphLoader.loadRoadMap("data/testdata/simpletest.map", theMap);

* System.out.println("DONE.");

*/

// more advanced testing

System.out.print("Making a new map...");

MapGraph theMap = new MapGraph();

System.out.print("DONE. \nLoading the map...");

GraphLoader.loadRoadMap("data/testdata/simpletest.map", theMap);

System.out.println("DONE.");

System.out.println("Num nodes: " + theMap.getNumVertices());

System.out.println("Num edges: " + theMap.getNumEdges());

List<GeographicPoint> route = theMap.bfs(new GeographicPoint(1.0, 1.0), new


GeographicPoint(8.0, -1.0));
System.out.println(route);

// Use this code in Week 3 End of Week Quiz MapGraph

theMap = new MapGraph();

System.out.print("DONE. \nLoading the map...");

GraphLoader.loadRoadMap("data/maps/utc.map", theMap);

System.out.println("DONE.");

GeographicPoint start = new GeographicPoint(32.8648772, -117.2254046);

GeographicPoint end = new GeographicPoint(32.8660691, -117.217393);

route = theMap.dijkstra(start, end);

List<GeographicPoint> route2 = theMap.aStarSearch(start, end);

}
MAPEDGE.java
package roadgraph;

import geography.GeographicPoint;

/**
* @author UCSD Intermediate Programming MOOC team
*
* A directed edge in a map graph from Node start to Node end
*/
class MapEdge
{
/** The name of the road */
private String roadName;

/** The type of the road */


private String roadType;

/** The two endpoints of the edge */


private MapNode start;
private MapNode end;

/** The length of the road segment, in km */


private double length;

static final double DEFAULT_LENGTH = 0.01;

/** Create a new MapEdge object


*
* @param roadName
* @param n1 The point at one end of the segment
* @param n2 The point at the other end of the segment
*
*/
MapEdge(String roadName, MapNode n1, MapNode n2)
{
this(roadName, "", n1, n2, DEFAULT_LENGTH);
}

MapEdge(String roadName, String roadType, MapNode n1, MapNode n2)


{
this(roadName, roadType, n1, n2, DEFAULT_LENGTH);
}

MapEdge(String roadName, String roadType,


MapNode n1, MapNode n2, double length)
{
this.roadName = roadName;
start = n1;
end = n2;
this.roadType = roadType;
this.length = length;
}
// retorna el mapnode del punto final
MapNode getEndNode() {
return end;
}

// retorna la localizacion del punto inicial


GeographicPoint getStartPoint()
{
return start.getLocation();
}

// retorna la localizacion del punto final


GeographicPoint getEndPoint()
{
return end.getLocation();
}

// retorna la longitud
double getLength()
{
return length;
}

// retorna el nombre del camino


public String getRoadName()
{
return roadName;
}

// dando un nodo y una arista, retorna el otro nodo


MapNode getOtherNode(MapNode node)
{
if (node.equals(start))
return end;
else if (node.equals(end))
return start;
throw new IllegalArgumentException("Looking for " +
"a point that is not in the edge");
}

// retorna un string que contiene detalles de la arista


public String toString()
{
String toReturn = "[EDGE between ";
toReturn += "\n\t" + start.getLocation();
toReturn += "\n\t" + end.getLocation();
toReturn += "\nRoad name: " + roadName + " Road type: " +
roadType +
" Segment length: " + String.format("%.3g",
length) + "km";

return toReturn;
}

}
/**
* Clase que representa un nodo en el Mapa
*/
package roadgraph;

import java.util.HashSet;
import java.util.Set;

import geography.GeographicPoint;

/**
* @author UCSD MOOC development team
*
* Class representing a vertex (or node) in our MapGraph
*
*/
// WEEK 3 SOLUTIONS implementando comparable
class MapNode implements Comparable
{
/** la lista de aristas fuera de este nodo */
private HashSet<MapEdge> edges;

/** la latitud y longitud en este nodo */


private GeographicPoint location;

// WEEK 3 SOLUTIONS

/** la distancia predecida de este nodo (usando algoritmo de la


semana 3) */
private double distance;

/** la distancia actual desde este nodo desde el inicio (usano


algoritmo de la semana 3) */
private double actualDistance;

// END WEEK 3 SOLUTIONS

MapNode(GeographicPoint loc)
{
location = loc;
edges = new HashSet<MapEdge>();
distance = 0.0;
actualDistance = 0.0;
}

void addEdge(MapEdge edge)


{
edges.add(edge);
}

/** Retorna los vecinos en este Mapnode */


Set<MapNode> getNeighbors()
{
Set<MapNode> neighbors = new HashSet<MapNode>();
for (MapEdge edge : edges) {
neighbors.add(edge.getOtherNode(this));
}
return neighbors;
}

/** gobtener la localizacion del nodo */


GeographicPoint getLocation()
{
return location;
}

/** retornar las aristas de este nodo */


Set<MapEdge> getEdges()
{
return edges;
}

/** retorna cuando 2 nodos son iguales.


* Los nodos son considerados iguales si su localizacion es la
misma,
* aunque su lista de calles sean diferentes.
*/
public boolean equals(Object o)
{
if (!(o instanceof MapNode) || (o == null)) {
return false;
}
MapNode node = (MapNode)o;
return node.location.equals(this.location);
}

/** debido a que compara nodos usando su localizacion, tambien


* podemos usar su localizacion para el HashCode.
* @Retornando el HashCode para este nodo, el cual es el Hashcode
* para el punto subyacente.
*/
public int HashCode()
{
return location.hashCode();
}

/** ToString to print out a MapNode method


* @return the string representation of a MapNode
*/
public String toString()
{
String toReturn = "[NODE at location (" + location + ")";
toReturn += " intersects streets: ";
for (MapEdge e: edges) {
toReturn += e.getRoadName() + ", ";
}
toReturn += "]";
return toReturn;
}
public String roadNamesAsString()
{
String toReturn = "(";
for (MapEdge e: edges) {
toReturn += e.getRoadName() + ", ";
}
toReturn += ")";
return toReturn;
}

// WEEK 3 SOLUTIONS

// obtener distancia del nodo (predicha)


public double getDistance() {
return this.distance;
}

// colocar distancia del nodo(predicha)


public void setDistance(double distance) {
this.distance = distance;
}

// obtener distancia del nodo(actual)


public double getActualDistance() {
return this.actualDistance;
}

// colocar distancia del nodo (actual)


public void setActualDistance(double actualDistance) {
this.actualDistance = actualDistance;
}

// codigo para implementar comparable


public int compareTo(Object o) {
// convertir el Mapnode, puede haber excepciones
MapNode m = (MapNode)o;
return
((Double)this.getDistance()).compareTo((Double)m.getDistance());
}

// END WEEK 3 SOLUTIONS


}

You might also like