Most Stones Removed with Same Row or Column
Medium
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: 5Example 2:
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3Example 3:
Input: stones = [[0,0]]
Output: 0Note:
1 <= stones.length <= 10000 <= stones[i][j] < 10000
Analysis & Solution
关键思路在于转化问题为Number of Islands:
每次移除的stone必须是一个属于connected component(也就是一个island)中的坐标,那么最后剩余的,就将是每个island都最后一个点。因此总的可以移除的stone数目:number os stones to be removed = total number of stones - number of islands
Union Find 并查集
HashMap implementation of Union Find
966 ms, faster than 0.98%
Array Implementation of Union Find
Time Complexity: O(NlogN), where N is the length of
stones. (If we used union-by-rank, this can be O(N∗α(N)), where α is the Inverse-Ackermann function.)Space Complexity: O(N).
DFS
Recursive Implementation
Stack Implementation
Last updated
Was this helpful?