编写程序对给定的有向图(不一定连通)进行深度优先遍历,图中包含n个顶点,编号为0至n-1。本题限定在深度优先遍历过程中,如果同时出现多个待访问的顶点,则优先选择编号最小的一个进行访问,以顶点0为遍历起点。
输入格式:
输入第一行为两个整数n和e,分别表示图的顶点数和边数,其中n不超过20000,e不超过50。接下来e行表示每条边的信息,每行为两个整数a、b,表示该边的端点编号,但各边并非按端点编号顺序排列。
输出格式:
输出为一行整数,每个整数后一个空格,即该有向图的深度优先遍历结点序列。
输入样例1:
3 3
0 1
1 2
0 2
输出样例1:
0 1 2
输入样例2:
4 4
0 2
0 1
1 2
3 0
输出样例2:
0 1 2 3
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 50;
int h[N],idx; //h[i]看成指向元素节点的指针
struct node
{
int to;
int next;
}e[N];
int n,m;
bool st[N];
void dfs(int i)
{
cout<<i<<" ";
st[i] = true;
for(int j = h[i];j!=0;j = e[j].next)
if(!st[e[j].to]) dfs(e[j].to);
}
void DFST()
{
for(int i=0;i<n;i++)
if(!st[i]) dfs(i);
}
void add(int u,int v)
{
e[++idx].to = v;
e[idx].next = h[u];
h[u] = idx;
}
int main()
{
cin>>n>>m;
while(m--)
{
int l,r;
cin>>l>>r;
add(l,r);
}
vector<int> temp; //vector相当于一个数组,完全可以当做数组使用
for(int i=0;i<n;i++)
{
for(int j=h[i];j!=0;j=e[j].next) temp.push_back(e[j].to);
sort(temp.begin(),temp.end());
int k=0;
for(int j = h[i];j!=0;j=e[j].next)
{
// e[j].to = *temp.begin();
// temp.erase(temp.begin());
e[j].to = temp[k++];
}
}
DFST();
return 0;
}