# 代码实现

``````//
// main.cpp
// DFS
//
// Created by Alps on 15/4/1.
//

#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{
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].color = WHITE;
for (int j = 0; j < outDegree; j++) {
temp = (VList)malloc(sizeof(struct node));
scanf("%d %d", &temp->val, &temp->weight);
}
}
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();
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;
}
``````

``````2
2 1
4 1
0
1
2 1
2
2 1
3 1``````

``输出： 1 2 4 3``

原文作者：数据结构之图
原文地址: https://blog.csdn.net/alps1992/article/details/44808041
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。