#DFS Graph

3 messages · Page 1 of 1 (latest)

livid dome
#

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;
    }
barren drumBOT
#

This post has been reserved for your question.

Hey @livid dome! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.