問題描述
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
import java.util.HashSet;
import java.util.Scanner;
public class RootePlant{
static int[] pre;
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int m=scanner.nextInt();
int n=scanner.nextInt();
int k=scanner.nextInt();
pre=new int[m*n+1];
for(int i=1;i<=m*n;i++) {
pre[i]=i;
}
for(int i=0;i<k;i++) {
int a=scanner.nextInt();
int b=scanner.nextInt();
union(a,b);
}
HashSet<Integer> set=new HashSet<Integer>();
for(int i=1;i<=m*n;i++) {
set.add(find(i));
}
System.out.println(set.size());
}
public static int find(int x) {
int x_root=x;
while(pre[x_root]!=x_root) {
x_root=pre[x_root];
}
return x_root;
}
public static void union(int x,int y) {
int x_root=find(x);
int y_root=find(y);
if(x_root!=y_root) {
pre[y_root]=x;
}
}
}