Leetcode: Most Stones Removed with Same Row or Column
2024-08-26 11:54:46
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);
}
}
}
最新文章
- ScrollView分栏视图分析
- django models进行数据库增删查改
- python模块httplib的使用
- 提高php开发效率的9大代码片段
- Jmeter+jenkins接口性能测试平台实践整理(一)
- C#导出
- kafka安装及常用命令
- syntax error near unexpected token `then&#39;
- oracle logminer全解析
- -bash: ulimit: open files: cannot modify limit: Operation not permitted
- Orchard 源码探索(Module,Theme,Core扩展加载概述)
- web socket教程
- 【NOIP2014】子矩阵
- 忘记root密码,进入单用户模式修改密码
- Prime Ring Problem(dfs水)
- [20181130]hash冲突导致查询缓慢.txt
- steps/align_si.sh
- Ubuntu 14.10 下安装伪分布式hive-0.14.0
- python - package - bs4 - 美味汤
- mybatis插入语句空值没有设置jdbcType报错
热门文章
- 关于bat文件的批处理
- Immediate Decodability UVA-644(qsort排序 + 模拟)
- nginx 配置文件详解(转)
- SpringBoot 注册Servlet三大组件【Servlet、Filter、Listener】-原生代码+@Bean+效果展示
- flask处理数据,页面实时刷新展示
- machine learning (5)---learning rate
- 题解 UVa10780
- VC中文件路径问题
- vue中input输入第一个字符时,光标会消失,需要再次点击才能输入
- Linux rpm安装指定安装路径