leetcode-947. 移除最多的同行或同列石头

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;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值