理解bfs的本质
- 求最短距离
- 因为bfs是通过不断往周围一层扩展,第一次到的距离即为最短距离
注意的点:
不要让同一个元素 同时在队列里面
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环。
所有边的长度都是 1,点的编号为 1∼n。
请你求出 1 号点到 n 号点的最短距离,如果从 1 号点无法走到 n 号点,输出 −1。
输入格式
第一行包含两个整数 n 和 m。
接下来 m 行,每行包含两个整数 a 和 b,表示存在一条从 a 走到 b 的长度为 1 的边。
输出格式
输出一个整数,表示 1 号点到 n 号点的最短距离。
数据范围
1≤n,m≤10^5
输入样例:
4 5 1 2 2 3 3 4 1 3 1 4
输出样例:
1
// 邻接矩阵,g[N][N]超内存
// 邻接表
import java.io.*;
import java.util.*;
class Main{
static int N = 100010;
static int n,m,idx;
static int[] h = new int[N];
static int[] e = new int[N];
static int[] ne = new int[N];
static int[] d = new int[N]; // 保存距离
static boolean[] st = new boolean[N]; // 保证队列中没有重复的元素
static Queue<Integer> q = new LinkedList<>();
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s = in.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
for(int i=1;i<=n;i++) // 初始化表头
h[i] = -1;
while(m-->0){ // 添加边
s = in.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
if(a!=b) // 避免自环
add(a,b);
}
// 将起始节点加入到队列
d[1] = 0;
q.add(1);
st[1] = true;
while(!q.isEmpty()){ // 当队列不为空
int t = q.poll();
st[t] = false;
for(int i=h[t];i!=-1;i=ne[i]){ // 遍历以t为头结点的链表
int j = e[i];
if(d[j]==0&&st[j]!=true){ // 当距离还为0(没有走到过该点)且当前点不在列表中
q.add(j);
st[j] = true;
d[j] = d[t]+1;
}
}
}
if(d[n]!=0) System.out.println(d[n]);
else if(n==1) System.out.println(0);
else System.out.println("-1");
}
// 添加边
public static void add(int a,int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}