简单的并查集就可以解决,详情可以看我的上一条博客
import java.io.*;
import java.util.HashSet;
public class Main {
static int num = 0; //合根植物
static int bian = 0; //编号
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
int m = Integer.parseInt(str[0]);
int n = Integer.parseInt(str[1]);
int k = Integer.parseInt(br.readLine());
bian = n*m;
int set[] = new int[bian+1];
init(set);
for(int i = 0 ; i < k;i++) {
String[] s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
union(a,b,set);
}
HashSet<Integer> hs = new HashSet<>();
for(int i = 1; i < set.length;i++) {
hs.add(find(set[i],set));
}
System.out.println(hs.size());
}
//初始化
static void init(int[] set) {
for(int i =1;i<set.length;i++) {
set[i] = i;
}
}
static void union(int a , int b,int[] set) {
//如果根结点相等
if(find(a,set) == find(b,set)) {
return;
}
//如果根结点不同,则让他们连接起来
set[find(a,set)] = find(b,set);
}
static int find(int n,int[] set) {
if(set[n] == n) {
return n;
}
return find(set[n],set);
}
}