Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Algorithms and Data Structures

Assignment 5: Maze Escape

Kylian Lahaye, 500805960.


Inhoudsopgave

Get All Vertices 3


Format Adjacency List 4
Depth First Search 6
Recursive Depth First Search 7
Breadth First Search 8
Dijkstra Shortest Path 10
Get All Vertices
public Set<V> getAllVertices(V firstVertex) {
Set<V> visited = new HashSet<>();
Stack<V> stack = new Stack<>();
stack.push(firstVertex);
visited.add(firstVertex);

while (!stack.isEmpty()) {
V current = stack.pop();
for (V neighbour : getNeighbours(current)) {
if (!visited.contains(neighbour)) {
visited.add(neighbour);
stack.push(neighbour);
}
}
}
return visited;
}

The code uses a depth-first search (DFS) algorithm to traverse a graph starting from
a given vertex. It maintains a set of visited vertices and a stack to track the vertices
to be processed.
Starting with the initial vertex, the code explores its neighbors one by one. If a
neighbor has not been visited, it is marked as visited and added to the stack for
further exploration.
This process continues until all reachable vertices have been visited. Finally, the set
of visited vertices is returned as the result.
Format Adjacency List
public String formatAdjacencyList(V firstVertex) {
StringBuilder stringBuilder = new StringBuilder("Graph
adjacency list:\n");
return
stringBuilder.append(this.formatAdjacencyListHelper(firstVertex,
new HashSet<>(), new StringBuilder())).toString();
}

private StringBuilder formatAdjacencyListHelper(V vertex, Set<V>


allVertices, StringBuilder stringBuilder) {
if (allVertices.contains(vertex)) {
return stringBuilder;
}

allVertices.add(vertex);

stringBuilder.append(vertex).append( ": ");

stringBuilder.append(this.getNeighbours(vertex).toString().replace
(", ", ",")).append("\n");

for (V child : this.getNeighbours(vertex)){


formatAdjacencyListHelper(child, allVertices,
stringBuilder);
}

return stringBuilder;
}
The code generates a formatted adjacency list representation of a graph. It starts
with a given vertex and initializes a StringBuilder object.
The formatAdjacencyListHelper method is called to process the vertex and its
neighbors. It checks if the vertex has already been visited. If not, it adds the vertex to
the visited set and appends the vertex name followed by a colon to the StringBuilder.
Next, it retrieves the neighbors of the vertex and appends them to the StringBuilder,
formatting the list representation.
The method then recursively calls itself for each neighbor to continue the process.
Finally, the method returns the StringBuilder object containing the formatted
adjacency list as a string.
In short, the code recursively processes the vertices and their neighbors to generate
a formatted adjacency list representation of a graph.
Depth First Search
public GPath depthFirstSearch(V startVertex, V targetVertex) {
if (startVertex == null || targetVertex == null){
return null;
}

GPath gPath = new GPath();


Deque<V> set = this.RecursiveDepthFirstSearch(startVertex,
targetVertex, gPath);

if (set == null) {
return null;
}
gPath.vertices = set;

return gPath;
}
The code searches for a path between two vertices (startVertex and targetVertex) in
a graph using a depth-first search (DFS) algorithm.
If either the start or target vertex is missing (null), the method returns null.
The code creates a path object (GPath) and calls a helper method to perform the
DFS search. If no path is found, null is returned.
If a path is found, the vertices along the path are stored in the path object.
Finally, the method returns the path object if a path was found, or null if no path
exists.
In short, the code searches for a path between two vertices using DFS and returns
the path if found, or null if not found.
Recursive Depth First Search
private Deque<V> RecursiveDepthFirstSearch(V currentVertex, V
targetVertex, GPath gPath) {
if (gPath.visited.contains(currentVertex)) {
return null;
}

if (currentVertex.equals(targetVertex)) {
Deque<V> path = new LinkedList<>();
path.addLast(currentVertex);
gPath.visited.add(currentVertex);
return path;
}

gPath.visited.add(currentVertex);

for (V child : this.getNeighbours(currentVertex)) {


Deque<V> path = RecursiveDepthFirstSearch(child,
targetVertex ,gPath);
if (path != null) {
path.addFirst(currentVertex);
gPath.visited.add(currentVertex);
return path;
}
}
return null;
}
The code is a recursive method that performs a depth-first search (DFS) to find a
path between two vertices in a graph. It explores the graph by visiting neighboring
vertices and backtracking when necessary. If a path is found, it is returned;
otherwise, null is returned to indicate no valid path exists.
Breadth First Search
public GPath breadthFirstSearch(V startVertex, V targetVertex) {
if (startVertex == null || targetVertex == null) {
return null;
}

GPath path = new GPath();


path.visited.add(startVertex);

Queue<V> queue = new LinkedList<>();


queue.add(startVertex);

Map<V, V> parents = new HashMap<>();


parents.put(startVertex, null);

while (!queue.isEmpty()) {
V current = queue.remove();

if (current.equals(targetVertex)) {
List<V> pathVertices = new ArrayList<>();
V vertex = targetVertex;
while (vertex != null) {
pathVertices.add(0, vertex);
vertex = parents.get(vertex);
}
path.getVertices().addAll(pathVertices);
return path;
}

for (V neighbor : getNeighbours(current)) {


if (!path.visited.contains(neighbor)) {
path.visited.add(neighbor);
queue.add(neighbor);
parents.put(neighbor, current);
}
}
}
return null;
}
The code uses a breadth-first search (BFS) algorithm to find a path between two
vertices in a graph. It explores the graph in a breadth-first manner, keeping track of
visited vertices and parent vertices. If a path is found, it is constructed by
backtracking from the target vertex to the start vertex. The resulting path is returned,
or null if no path exists.
Dijkstra Shortest Path
public GPath dijkstraShortestPath(V startVertex, V targetVertex,
BiFunction<V,V,Double>
weightMapper) {

if (startVertex == null || targetVertex == null) return null;

GPath path = new GPath();


path.visited.add(startVertex);

if (startVertex.equals(targetVertex)) {
path.vertices.add(startVertex);
return path;
}

Map<V, MSTNode> minimumSpanningTree = new HashMap<>();

MSTNode nearestMSTNode = new MSTNode(startVertex);


nearestMSTNode.weightSumTo = 0.0;
minimumSpanningTree.put(startVertex, nearestMSTNode);

path.vertices.addLast(targetVertex);

while (nearestMSTNode != null) {

path.visited.add(nearestMSTNode.vertex);

if (nearestMSTNode.vertex.equals(targetVertex)){
V prevVertex = nearestMSTNode.parentVertex;

while (prevVertex != null){


path.vertices.addFirst(prevVertex);
prevVertex =
minimumSpanningTree.get(prevVertex).parentVertex;
}
path.totalWeight = nearestMSTNode.weightSumTo;
return path;
}

nearestMSTNode =
findNextNearestMSTNode(minimumSpanningTree, weightMapper);
}
return null; // replace by a proper outcome, if any
}
The code uses Dijkstra's algorithm to find the shortest path between two vertices in a
graph. It maintains a minimum spanning tree (MST) to track visited vertices, their
predecessors, and the total weight of the shortest path. It constructs the path by
backtracking from the target vertex to the start vertex using the MST's information.
The resulting path and its total weight are returned, or null if no path exists.

Code snippet 7 is missing because these are the only 6 methods I worked on…

You might also like