有遍历顺序,从小到大
图的bfs
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n, m;
const int N = 100010;
int h[N], e[N], ne[N], idx;
void add(int a, int b) // 添加一条边a->b
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int q[N], d[N];
vector<int> ans;
int bfs()
{
int hh = 0, tt = -1;
memset(d, -1, sizeof d);
d[1] = 0;
q[++ tt] = 1;
ans.push_back(1);
while (hh <= tt)
{
int t = q[hh ++];
vector<int> p;
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (d[j] == -1)
{
p.push_back(j);
}
}
sort(p.begin(), p.end());
for (int i = 0; i < p.size(); i ++)
{
ans.push_back(p[i]);
d[p[i]] = d[t] + 1;
q[++ tt] = p[i];
}
}
return d[n];
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while (m --)
{
int a, b;
cin >> a >> b;
add(a, b);
}
int t = bfs();
if (t == -1)
{
return -1;
}
else
{
for (int i = 0; i < n; i++ )
{
cout << ans[i] << ' ';
}
}
return 0;
}
图的dfs
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, m;
int h[N], e[N], ne[N], idx;
void add(int a, int b) // 添加一条边a->b
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
bool st[N];
vector<int> res;
void dfs(int u)
{
if (st[u])
return ;
res.push_back(u);
st[u] = true;
vector<int> p;
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
p.push_back(j);
}
}
sort(p.begin(), p.end());
for (int i = 0; i < p.size(); i++)
{
dfs(p[i]);
}
return ;
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
while (m -- )
{
int a, b;
cin >> a >> b;
add(a, b);
}
dfs(1);
if (res.size() != n)
{
return -1;
}
else
{
for (int i = 0; i < res.size(); i++)
{
cout << res[i] << ' ';
}
}
return 0;
}