Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- /* The graphs used in the post's diagrams
- have node indexing which starts at 1.
- Since arrays and vectors in C++ use
- 0-based indexing, we subtract 1 from the
- indices used in the input, and add 1
- to the indices printed in the output. */
- /* This graph can support 10000 nodes
- numbered from 1 to 10000 inclusive. */
- bool visited[10000] = {false};
- /* Each vector of integers represents
- an individual node and the nodes it
- is connected with. */
- vector< vector<int> > adjList;
- /* Every time 'Recur' is called, the node
- at index is visited. We then recur for each
- unvisited node which is connected
- to the node at index. */
- void Recur (int index) {
- cout << index+1 << "\n";
- visited[index] = true;
- for (int i = 0; i < adjList[index].size(); i++) {
- if (!visited[adjList[index][i]]) {
- Recur(adjList[index][i]);
- }
- }
- }
- int main () {
- /* Take the number of nodes in the graph
- and the number of edges in the graph as input. */
- int nodeCount, edgeCount;
- cin >> nodeCount >> edgeCount;
- /* Fill the adjacency list with unconnected nodes. */
- for (int i = 0; i < nodeCount; i++) {
- vector<int> node;
- adjList.push_back (node);
- }
- /* Add undirected edges to the adjacency list
- using the input as a guide. */
- for (int i = 0; i < edgeCount; i++) {
- int n1, n2;
- cin >> n1 >> n2;
- n1--;
- n2--;
- adjList[n1].push_back (n2);
- adjList[n2].push_back (n1);
- }
- /* Finally, take the index of the starting node,
- and begin the depth-first traversal at this index. */
- int startIndex;
- cin >> startIndex;
- startIndex--;
- Recur (startIndex);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement