Algorithm learning, algorithm Learning Website
Deep priority Traversal
In graph traversal, depth-first traversal and breadth-first traversal are the most common and simplest traversal methods.
The idea of depth-first traversal is to keep looking down and find other branches after finding the end.
In my previous blog, I wrote the breadth-first traversal (BFS ).
Portal to be viewed: The image's breadth is prioritized
Code Implementation
The difference between implementation and BFS is that in BFS, the container we use is queue (first-in-first-out), while in DFS, we need to use stack (stack) an advanced post-output container.
Other basic principles 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 4 using namespace std; struct node {int val; int weight; // if your graph is weight graph struct node * next; node (int v, int w): val (v ), weight (w), next (NULL) {}}; typedef node * VList; struct TableEntry {VList header; Vertex color;}; typedef TableEntry Table [NumVertex + 1]; void InitTableEntry (Vertex start, Table T) {Vertex outDegree; VList temp = NULL; for (int I = 1; I <= NumVertex; I ++) {scanf ("% d", & outDegree); T [I]. header = NULL; T [I]. color = WHITE; for (int j = 0; j <outDegree; j ++) {temp = (VList) malloc (sizeof (struct node )); scanf ("% d", & temp-> val, & temp-> weight); temp-> next = T [I]. header; T [I]. header = temp ;}t [start]. color = GRAY;} void DFS (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 ;}} int main (int argc, const char * argv []) {Table T; InitTableEntry (1, T ); DFS (1, T); return 0 ;}
Test cases:
22 14 1012 122 13 1
This is the input. The number of each row is the degree of output of the node, followed by its adjacent nodes.
Output: 1 2 4 3
So. This test case can also be used in BFS of my previous blog.