union the points who have the same row or col
我们把那两个点连起来
然后我们从一条路径的头开始走
import java.util.HashMap;
import java.util.Scanner;
public class Main {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
Solution s = new Solution();
HashMap<Integer, Integer> map = new HashMap<>();
while (T-- != 0) {
int N = scan.nextInt();
int M = scan.nextInt();
int[][] A = new int[N][M];
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j)
A[i][j] = scan.nextInt();
}
System.out.println(s.removeStones(A));
}
}
}
class Solution {
public int removeStones(int[][] stones) {
UF uf = new UF(stones);
for (int[] s1 : stones) {
String ss1 = s1[0] + " " + s1[1];
for (int[] s2 : stones) {
// two points have the same row or col
if (s1[0] == s2[0] || s1[1] == s2[1]) {
String ss2 = s2[0] + " " + s2[1];
uf.union(ss1, ss2);
}
}
}
return stones.length - uf.island;
}
}
class UF {
HashMap<String, String> map;
int island;
public UF(int[][] a) {
map = new HashMap<>();
for (int i = 0; i < a.length; ++i) {
String s = a[i][0] + " " + a[i][1];
map.put(s, s);
}
island = a.length;
}
public void union(String o1, String o2) {
// TODO Auto-generated method stub
String r1 = find(o1);
String r2 = find(o2);
if (r1 != r2) {
map.put(r1, r2);
--island;
}
}
private String find(String x) {
// TODO Auto-generated method stub
while (x != map.get(x)) {
x = map.get(x);
}
return x;
}
}