Depth-First traversal
In the traversal of graphs, depth-first traversal and breadth-first traversal are the most common and simplest of two traversal methods.
The idea of a depth-first traversal is to look down, find the end, and then look for other branches.
In the previous blog I have written breadth-first traversal (BFS).
Portals to look at: breadth-first traversal of graphs
Code implementation
The difference between the implementation and BFS here is that in BFS we use a queue, which is FIFO, and in DFS we need to use a stack of advanced containers.
Other fundamentals are the same.
////Main.cpp//DFS////Created by Alps on 15/4/1.//Copyright (c) 2015 Chen. All rights reserved.//#include <iostream>#include <stack>#define VERTEX int#define WHITE 0#define GRAY 1#define BLACK 2#define NUMVERTEX 4using namespace STD;structnode{intValintWeight//If your graph is weight graph structNode* Next; NodeintVintW): Val (v), weight (W), Next (NULL) {}};typedefnode* VList;structtableentry{VList Header; Vertex color;};typedefTableentry table[numvertex+1];voidInittableentry (Vertex start, Table T) {Vertex outdegree; VList temp = NULL; for(inti =1; I <= Numvertex; i++) {scanf("%d", &outdegree); T[i].header = NULL; T[i].color = white; for(intj =0; J < Outdegree; J + +) {temp = (VList)malloc(sizeof(structnode));scanf("%d%d", &temp->val, &temp->weight); Temp->next = T[i].header; T[i].header = temp; }} T[start].color = GRAY;}voidDFS (Vertex start, Table T) { Stack<Vertex>S S.push (start); Vertex V; VList temp; while(! S.empty ()) {V = S.top ();printf("%d", V); T[v].color = BLACK; S.pop (); temp = T[v].header; while(temp) {if(T[temp->val].color = = white) {S.push (temp->val); T[temp->val].color = GRAY; } temp = temp->next; } }}intMainintargcConst Char* argv[]) {Table T; Inittableentry (1, T); DFS (1, T);return 0;}
Test Case:
22 14 1012 122 13 1
This is the input, the number of each row is the node out, followed by its adjacent nodes.
输出: 1 2 4 3
So. This test case can also be used in the BFS of my last blog post.
Algorithm learning-depth-first traversal of graphs (DFS) (c + +)