输入样例:
4 5
1 2
2 3
3 4
1 3
1 4
输出样例:
1
算法思路:
通过邻接表建立有向图,因为是找的最短路,并且各边权值为1,所以用宽搜。
Java代码:
import java.io.*;
import java.util.*;
public class Main {
static int n, m;
static int []dis;
static int []e;
static int []ne;
static int []h;
static int idx;
static boolean []vis;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] split = br.readLine().split(" ");
n = Integer.parseInt(split[0]);
m = Integer.parseInt(split[1]);
e = new int[m];
ne = new int[m];
h = new int[n + 1];
vis = new boolean[n + 1];
dis = new int[n + 1];
Arrays.fill(h, -1);
for(int i = 0; i < m; i++) {
split = br.readLine().split(" ");
int a = Integer.parseInt(split[0]);
int b = Integer.parseInt(split[1]);
add(a, b);
}
bfs();
}
public static void bfs() {
Queue<Integer> qu = new LinkedList<>();
qu.add(1);
vis[1] = true;
while(!qu.isEmpty()) {
Integer u = qu.poll();
if(u == n) {
System.out.println(dis[u]); // 注意下标
return;
}
for(int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if(!vis[j]) {
qu.add(j);
vis[j] = true;
dis[j] = dis[u] + 1;
}
}
}
System.out.println("-1"); // 没有路径
}
public static void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}