847. 图中点的层次 Java题解 (bfs)

32 篇文章 1 订阅
30 篇文章 1 订阅

输入样例:

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++;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值