Reputation: 55
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
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
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