I have written code to find whether the path exists between source and destination in a directed graph. I have used BFS and instead of ArrayList
or queue. I have written my own helper class.
Please let me know how the code can be improved.
public class Graph {
private int numVertex;
// Helper class, which can act like Adjacency List or Queue for BFS search.
private HelperClass[] adjList;
public Graph(int n) {
numVertex = n;
adjList = new HelperClass[n];
for (int i = 0; i < n; i++) {
adjList[i] = new HelperClass();
}
}
public void setAdjacencyList(HelperClass[] adjList) {
this.adjList = adjList;
}
// Assuming that source and destination will be in the range of vertices.
public boolean isPathExists(int source, int destination) {
if (source == destination)
return true;
// else do BFS until the destination is found or all the nodes are
// visited.
HelperClass hc = new HelperClass();
boolean[] isVisited = new boolean[numVertex];
hc.add(source);
isVisited[source] = true;
while (!hc.isEmpty()) {
int current = hc.poll();
if (current == destination) {
return true;
}
int leftIndex = adjList[current].first;
int rightIndex = adjList[current].last;
while (leftIndex < rightIndex) {
int temp = adjList[current].array[leftIndex++];
if (!isVisited[temp]) {
hc.add(temp);
}
}
}
return false;
}
public static class HelperClass {
// assuming the maximum array size will not be more than 10000.
int[] array = new int[10000];
int first = 0;
int last = 0;
public void add(int x) {
array[last++] = x;
}
public int poll() {
if (!isEmpty()) {
return array[first++];
} else {
return -1;
}
}
public boolean isEmpty() {
return first == last ? true : false;
}
}
}