website/content/ChapterFour/0900~0999/0947.Most-Stones-Removed-with-Same-Row-or-Column.md
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 <= 10000 <= stones[i][j] < 10000在二维平面上,我们将石头放置在一些整数坐标点上。每个坐标点上最多只能有一块石头。现在,move 操作将会移除与网格上的某一块石头共享一列或一行的一块石头。我们最多能执行多少次 move 操作?
提示:
union() 起来。不同集合之间是不能相互移除的。反证法:如果能移除,代表存在共行或者共列的情况,那么肯定是同一个集合了,这样就不满足不同集合了。最终剩下的点就是集合的个数,每个集合只会留下一个点。所以移除的点就是点的总数减去集合的个数 len(stones) - uf.totalCount()。
package leetcode
import (
"github.com/halfrost/leetcode-go/template"
)
func removeStones(stones [][]int) int {
if len(stones) <= 1 {
return 0
}
uf, rowMap, colMap := template.UnionFind{}, map[int]int{}, map[int]int{}
uf.Init(len(stones))
for i := 0; i < len(stones); i++ {
if _, ok := rowMap[stones[i][0]]; ok {
uf.Union(rowMap[stones[i][0]], i)
} else {
rowMap[stones[i][0]] = i
}
if _, ok := colMap[stones[i][1]]; ok {
uf.Union(colMap[stones[i][1]], i)
} else {
colMap[stones[i][1]] = i
}
}
return len(stones) - uf.TotalCount()
}