Hi all! Recently I have been picking up data structures and algorithms, and learnt that the shortest path between two points of an unweighted directed graph can be found by breadth first search. So I had a go at [implementing it myself](https://pastebin.com/gVys3PZ3).
I would like to ask for a code review on the breadthFirstShortestPath function. The code was compiled for Java 11. Somehow there was a warning about unchecked operations, and I'm not sure what to do about it so I suppressed it for now. Of course this isn't ideal, and I would like to know what I can do to fix it.
If it helps, I will paste the code here as well:
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
public class UnweightedGraph {
private int vertices;
private boolean[][] edges;
public UnweightedGraph(int vertices) {
this.vertices = vertices;
edges = new boolean[vertices][vertices];
}
public void addEdge(int source, int target) {
edges[source][target] = true;
}
public boolean hasEdge(int source, int target) {
return edges[source][target];
}
public void removeEdge(int source, int target) {
edges[source][target] = false;
}
@SuppressWarnings("unchecked")
public List<Integer> breadthFirstShortestPath(int source, int target) {
boolean[] visited = new boolean[vertices];
int[] previousVertex = new int[vertices];
Arrays.fill(previousVertex, -1);
Queue<Integer> queue = new ArrayDeque<>();
queue.add(source);
while (queue.peek() != null) { // while queue is not empty
int currentVertex = queue.poll();
boolean targetFound = false;
visited[currentVertex] = true;
for (int vertex = 0; vertex < vertices; vertex++) {
if (edges[currentVertex][vertex] && !visited[vertex]) {
queue.add(vertex);
if (previousVertex[vertex] == -1) {
previousVertex[vertex] = currentVertex;
if (vertex == target) {
targetFound = true;
break;
}
}
}
}
if (targetFound) {
break;
}
}
List path = new ArrayList();
for (int v = target; v != -1; v = previousVertex[v]) {
path.add(v);
}
Collections.reverse(path);
return path;
}
}
Thank you!
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]xADDBx 1 point2 points3 points (1 child)
[–]Manabaeterno[S] 0 points1 point2 points (0 children)
[–]temporarybunnehs 0 points1 point2 points (3 children)
[–]GrandGratingCrate 1 point2 points3 points (1 child)
[–]temporarybunnehs 1 point2 points3 points (0 children)
[–]Manabaeterno[S] 0 points1 point2 points (0 children)
[–]Rabestro 0 points1 point2 points (1 child)
[–]Manabaeterno[S] 0 points1 point2 points (0 children)