user3154554
user3154554

Reputation: 55

How to iterate over all nodes in a graph?

I have a directed graph and want to iterate over all the nodes in the graph.

So what is the way in which I can iterate over all the graphs?

Upvotes: 1

Views: 8526

Answers (2)

dorr
dorr

Reputation: 816

In the toString() method, there is an example of iterating over all the nodes:

for (int v = 0; v < V; v++) {
    s.append(String.format("%d: ", v));
    for (int w : adj[v]) {
        s.append(String.format("%d ", w));
    }
    s.append(NEWLINE);
}

Notice that nodes are simple ints; there are graph.V() nodes, and they are numbered 0 to graph.V() - 1. That means you can iterate through them with a simple for loop, as above.

Upvotes: 1

mushfek0001
mushfek0001

Reputation: 3935

The data structure you are using stores the graph as an adjacency list in the memory. So just take a single node as source/start node and run any standard graph traversal algorithm (e.g. BFS or DFS) from there to iterate over all the nodes.

Upvotes: 0

Related Questions