I have a DFS search algorithm but does anyonw know how I could change it so that it returns how many graph it is searching? My algorithm first searched 1 graph and returned if two vertices are connected by a path with charging stations on each itermediate vertex but now I want it to search 2 disconnected graphs and return that it is searching 2 disconnected graphs? I have attached an image of the graph and my code.
public boolean isConnectedWithChargingStations(Vertex startVertex, Vertex endVertex) {
// Sanity check
if (startVertex.getIndex() == endVertex.getIndex()) {
return true;
}
Stack<Vertex> searchStack = new Stack<Vertex>();
Set<Vertex> visited = new HashSet<>();
searchStack.push(startVertex);
while(!searchStack.isEmpty()){
Vertex vertex = searchStack.pop();
if (!visited.contains(vertex)) {
visited.add(vertex);
if (vertex == endVertex){
return true;
}
if (vertex.hasChargingStation() || vertex == startVertex){
for (Edge e : vertex.getIncidentRoads()) {
//System.out.println(e.toString());
Vertex neighbour = e.getFirstVertex();
if (!visited.contains(neighbour)) {
searchStack.push(neighbour);
}
neighbour = e.getSecondVertex();
if (!visited.contains(neighbour)) {
searchStack.push(neighbour);
}
}
}
}
}
return false;
}