0

enter image description here

Let's say we have the graph that is below and we want to print out all the vertices names that there are. How would I be able to reach vertice C if I start exploring at vertice A?

I would assume we use the following implementation for a graph:

class Node {
    public int val;
    public List<Node> neighbors;
    public Node() {
        val = 0;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val) {
        val = _val;
        neighbors = new ArrayL]ist<Node>();
    }
    public Node(int _val, ArrayList<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}

If we can't use this implementation, what implementation of a graph can I use so that if I run a depth first search or breadth first search on a directed graph, all of the vertices are discovered?

Shyam Vyas
  • 61
  • 4
  • If you use an implementation that ONLY relies on the directed neighbors, you will run into problems, as clearly when starting from A you could never reach C. Have a second List "secretNeighbors", and after you initialized the whole graph, let every Node 'contact' its neighbors (in your case C would call to G), and if there's no connection backwards (G to C), then G will put C in its "secretNeighbors" list. This way you still have a clean, separate access to your directed Vertices (Node-to-Node-connection), but you still can 'contact' every node on the graph that's in any way connected to start – JayC667 Mar 16 '21 at 22:57
  • Oh and btw: reachability has nothing to do with breadth-first or depth-first approaches. Depth-first is usually faster /more efficient at finding the shortest route, if you can provide secondary navigation heuristics, like GPS-coordinates on a map of cities with an estimate of distances / travel costs. Breadth-first is more efficient in flood-fill algorithms for min/max travel lengths. – JayC667 Mar 16 '21 at 23:02
  • Adjacency matrix/adjacency list may be better option here. – user882813 Mar 16 '21 at 23:13
  • Ohhh ok, thank you so much guys, that makes a lot of sense. Thanks @JayC667 and user882813 :) – Shyam Vyas Mar 16 '21 at 23:49

0 Answers0