总之就是把能扩展的点取出来,然后弹出,然后把能扩展的点都放进去,然后更新距离,最后输出最小值即可!
实际上我认为宽搜比深搜简单,如果会队列的话。
STL版队列
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100005, M = N * 2;
int n, m;
int h[N], e[M], ne[M], idx;
int d[N];
queue<int> q;
void add(int a, int b) // 添加一条边a->b
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
void bfs()
{
q.push(1);
d[1] = 0;
while (!q.empty())
{
int t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i] )
{
int j = e[i];
if (d[j] == -1)
{
d[j] = d[t] + 1;
q.push(e[i]);
}
}
}
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
memset(d, -1, sizeof d);
for (int i = 1; i <= m; i ++ )
{
int a, b;
cin >> a >> b;
add(a, b);
}
bfs();//淦,居然没有调用函数
cout << d[n];
return 0;
}
手写版队列
#include<bits/stdc++.h>
using namespace std;
const int N = 100005;
int n, m;
int e[N], ne[N], h[N], idx;
int q[N], d[N];
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
int bfs()
{
q[0] = 1;//把第一个点放进队列
int hh = 0, tt = 0;
d[1] = 0;//第一个点的距离为0
while(hh <= tt)
{
int t = q[hh ++] ;//取出队头
for(int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if(d[j] == -1)
{
d[j] = d[t] + 1;
q[++tt] = j;
}
}
}
return d[n];
}
int main()
{
memset(h, -1, sizeof h);
memset(d, -1, sizeof d);
cin >> n >> m;
for(int i = 1;i <= m; i ++ )
{
int a, b;
cin >> a >> b;
add(a, b);
}
cout << bfs() <<endl;
return 0;
}