#include<bits/stdc++.h>
#define INF 99999999
#define MAX 1010
using namespace std;
/* 算法: 访问当前结点 递归进入当前结点的第一个连接且未被访问结点 直至退栈 */
class MGraph //矩阵图
{
public:
int n;
int **matrix;
MGraph(){ matrix = NULL; }
};
class LGraph //链式图
{
public:
vector<int> *vs;
int n;
LGraph(){ vs = NULL; }
};
MGraph* create_mGraph()
{
int i, from, to, vn, en; //点数、边数
MGraph *g = new MGraph();
scanf("%d%d", &vn, &en);
g->n = vn;
g->matrix = new int*[vn];
for(i = 0; i < vn; i++)
{
g->matrix[i] = new int[vn];
fill(g->matrix[i], g->matrix[i] + vn, 0);
}
for(i = 0; i < en; i++)
{
cin >> from >> to;
g->matrix[from][to] = 1;
//无向图加上 g->matrix[to][from] = 1;
}
return g;
}
LGraph *create_lGraph()
{
int i, from, to, vn, en; //点数、边数
LGraph *g = new LGraph();
scanf("%d%d", &vn, &en);
g->n = vn;
g->vs = new vector<int>[vn];
for(i = 0; i < en; i++)
{
cin >> from >> to;
g->vs[from].push_back(to);
//无向图加上 g->vs[to].push_back(from);
}
return g;
}
void DFSM(MGraph *mg, int s, int *visit)
{
if(mg->n <= 0 || s >= mg->n || s < 0)
return;
visit[s] = 1;
cout << s << " ";
for(int i = 0; i < mg->n; i++)
if(mg->matrix[s][i] != 0 && mg->matrix[s][i] != INF && !visit[i])
DFSM(mg, i, visit);
}
void DFSL(LGraph *lg, int s, int *visit)
{
if(lg->n <= 0 || s >= lg->n || s < 0)
return;
visit[s] = 1;
cout << s << " ";
for(int i = 0; i < lg->vs[s].size(); i++)
if(!visit[lg->vs[s][i]])
DFSL(lg, lg->vs[s][i], visit);
}
int main()
{
MGraph *mg = create_mGraph();
LGraph *lg = create_lGraph();
int visitM[MAX] = {0}, visitL[MAX] = {0};
for(int i = 0; i < mg->n; i++)
if(!visitM[i])
DFSM(mg, i, visitM);
cout << endl;
for(int i = 0; i < lg->n; i++)
if(!visitL[i])
DFSL(lg, i, visitL);
return 0;
}
/* input: 5 8 0 1 0 3 0 4 1 2 2 4 3 1 3 2 3 4 5 8 0 1 0 3 0 4 1 2 2 4 3 1 3 2 3 4 */
图的DFS周游
原文作者:骑士周游问题
原文地址: https://blog.csdn.net/qq_38206090/article/details/81942686
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/qq_38206090/article/details/81942686
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。