问题描述:
w星球的一个种植园,被分成 m * n 个小格子(东西方向m行,南北方向n列)。每个格子里种了一株合根植物。
这种植物有个特点,它的根可能会沿着南北或东西方向伸展,从而与另一个格子的植物合成为一体。
如果我们告诉你哪些小格子间出现了连根现象,你能说出这个园中一共有多少株合根植物吗?
输入格式:
第一行,两个整数m,n,用空格分开,表示格子的行数、列数(1<m,n<1000)。
接下来一行,一个整数k,表示下面还有k行数据(0<k<100000)
接下来k行,第行两个整数a,b,表示编号为a的小格子和编号为b的小格子合根了。
格子的编号一行一行,从上到下,从左到右编号。
比如:5 * 4 的小格子,编号:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
样例:
输入:
5 4 16 2 3 1 5 5 9 4 8 7 8 9 10 10 11 11 12 10 14 12 16 14 18 17 18 15 19 19 20 9 13 13 17
输出:
5
思路:
合根植物使用并查集(先并后查)的思想可以进行解答,定义一个pre数组存储每个植物的合根情况。在进行输入的时候将两个合根的植物合在一起,最终用set集合(不存储相同的元素)对合根的情况进行统计,输入set的长度。
代码:
import java.util.*;
public class Main {
static int[] pre;//用来标识合根的情况
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt(), n = sc.nextInt(), count = sc.nextInt();
int len = m * n;//len个植物
pre = new int[len + 1];
for (int i = 1; i <= len; i++) {
pre[i] = i;
}
while (count > 0) {
int x = sc.nextInt(), y = sc.nextInt();
join(x, y);
count--;
}
Set<Integer> set = new HashSet<>();
for (int i = 1; i <= len; i++) {
set.add(find(i));
}
System.out.println(set.size());
}
public static void join(int x, int y) {
int fx = find(x);
int fy = find(y);
//如果不相同,则进行赋值
if (fx != fy) {
pre[fx] = fy;
}
}
//不断进行查找
public static int find(int x) {
int father = x;
while (pre[father] != father) {
father = pre[father];
}
int i = x;
while (pre[i] != father) {
int j = pre[i];
pre[i] = father;
i = j;
}
return father;
}
}