Loading...

并查集-Leetcode947移除最多的同行或同列石头

在这里插入图片描述

求解代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
	public static HashMap<Integer,Integer> rowFirst = new HashMap<Integer,Integer>();
	public static HashMap<Integer,Integer> colFirst = new HashMap<Integer,Integer>();

	public static int MAXN = 1001;
	public static int[] father = new int[MAXN];

	public static int sets;

	public static void build(int n){
		rowFirst.clear();
		colFirst.clear();
		for(int i=0;i<n;i++){
			father[i]=i;
		}
		sets = n;
	}

	public static int find(int i){
		if (i!=father[i]) {
			father[i]=find(father[i]);
		}
		return father[i];
	}

	public static void union(int x,int y){
		int fx = find(x);
		int fy = find(y);
		if (fx!=fy) {
			father[fx]=fy;
			sets--;
		}
	}

	public static int removeStones(int[][] stones){
		int n = stones.length;
		build(n);

		for(int i =0;i<n;i++){
			int row = stones[i][0];
			int col = stones[i][1];
			if(!rowFirst.containsKey(row)){
				rowFirst.put(row, i);
			}else{
				union(i, rowFirst.get(row));
			}

			if(!colFirst.containsKey(col)){
				colFirst.put(col, i);
			}else{
				union(i, colFirst.get(col));
			}
		}
		return n-sets;
	}
最后更新于 2026-04-05 17:35:33
Code Road Record