On a 2D plane, we place stones at some integer coordinate points.  Each coordinate point may have at most one stone.

Now, a move consists of removing a stone that shares a column or row with another stone on the grid.

What is the largest possible number of moves we can make?

Example 1:

Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Example 2: Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Example 3: Input: stones = [[0,0]]
Output: 0 Note: 1 <= stones.length <= 1000
0 <= stones[i][j] < 10000

If stone a and stone b are in the same column/row, we connect them as a component

The largest possible number of moves we can make = the number of unions we can make = Total stones count - count of components.

 class Solution {
public int removeStones(int[][] stones) {
UnionFind uf = new UnionFind(stones.length);
int countUnion = 0;
for (int i = 0; i < stones.length - 1; i ++) {
for (int j = i + 1; j < stones.length; j ++) {
if (uf.isConnected(i, j)) continue;
if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) {
uf.union(i, j);
countUnion ++;
}
}
}
return countUnion;
} public class UnionFind {
int[] fathers; public UnionFind(int n) {
fathers = new int[n];
for (int i = 0; i < n; i ++) {
fathers[i] = i;
}
} public void union(int i, int j) {
int iRoot = find(i);
int jRoot = find(j);
fathers[jRoot] = iRoot;
} public int find(int i) {
while (i != fathers[i]) {
i = fathers[i];
}
return i;
} public boolean isConnected(int i, int j) {
return find(i) == find(j);
}
}
}

最新文章

  1. ScrollView分栏视图分析
  2. django models进行数据库增删查改
  3. python模块httplib的使用
  4. 提高php开发效率的9大代码片段
  5. Jmeter+jenkins接口性能测试平台实践整理(一)
  6. C#导出
  7. kafka安装及常用命令
  8. syntax error near unexpected token `then&#39;
  9. oracle logminer全解析
  10. -bash: ulimit: open files: cannot modify limit: Operation not permitted
  11. Orchard 源码探索(Module,Theme,Core扩展加载概述)
  12. web socket教程
  13. 【NOIP2014】子矩阵
  14. 忘记root密码,进入单用户模式修改密码
  15. Prime Ring Problem(dfs水)
  16. [20181130]hash冲突导致查询缓慢.txt
  17. steps/align_si.sh
  18. Ubuntu 14.10 下安装伪分布式hive-0.14.0
  19. python - package - bs4 - 美味汤
  20. mybatis插入语句空值没有设置jdbcType报错

热门文章

  1. 关于bat文件的批处理
  2. Immediate Decodability UVA-644(qsort排序 + 模拟)
  3. nginx 配置文件详解(转)
  4. SpringBoot 注册Servlet三大组件【Servlet、Filter、Listener】-原生代码+@Bean+效果展示
  5. flask处理数据,页面实时刷新展示
  6. machine learning (5)---learning rate
  7. 题解 UVa10780
  8. VC中文件路径问题
  9. vue中input输入第一个字符时,光标会消失,需要再次点击才能输入
  10. Linux rpm安装指定安装路径