107. 寻找存在的路径
可用 dfs 或 bfs,这里用并查集。
import java.util.Scanner;
public class Main {
static int n = 105; // n 根据题目中节点数量而定,一般比节点数量大一点就好
static int[] father = new int[n];
static { // 第一次加载类时就会执行
init();
}
// 初始化
static void init() {
for (int i = 0; i < n; i++) {
father[i] = i;
}
}
// 查找根节点(带路径压缩)
static int find(int a) {
if (a == father[a]) {
return a;
}
return father[a] = find(father[a]);
}
// 将两个元素添加到同一集合(路径压缩法)
static void join(int a, int b) {
a = find(a);
b = find(b);
if (a == b) { // 如果本来就在同一集合,直接返回
return;
}
father[a] = b; // 改变的是根的指向
}
// 判断两个元素是否在同一集合
static boolean isSame(int a, int b) {
a = find(a);
b = find(b);
return a == b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
while (k-- > 0) {
int s = sc.nextInt();
int t = sc.nextInt();
join(s, t);
}
int source = sc.nextInt();
int destination = sc.nextInt();
System.out.println(isSame(source, destination) ? 1 : 0);
}
}

被折叠的 条评论
为什么被折叠?



