On a 2D plane, n stones are placed at integer coordinate points. Each coordinate point holds at most one stone.
A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.
Given an array stones of length n where stones[i] = [x, y] is the location of the i-th stone, return the largest possible number of stones that can be removed.
Function Signature
def remove_stones(stones: list[list[int]]) -> int:
Rules
-
Two stones share a row when their
x
values are equal and share a column when their
y
values are equal.
-
Stones are removed one at a time. The condition is checked against the stones still on the plane at the moment of each removal, and you may choose any order.
Constraints
-
1 <= len(stones) <= 1000
-
0 <= x, y <= 10^4
-
No two stones are at the same coordinate point.
Examples
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
All six stones are linked through shared rows and columns, so every stone except one can go. One valid order removes [2,2], [2,1], [1,2], [1,0] and then [0,1], each while a stone in its row or column remains, which leaves [0,0].
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
The four corner stones are linked, so three of them can be removed (for example [2,2], then [2,0], then [0,2]). The stone at [1,1] shares no row or column with any other stone, so it can never be removed.
Input: stones = [[0,1],[1,0]]
Output: 0
The first stone is in row 0 and column 1, and the second is in row 1 and column 0. They share neither a row nor a column, so no stone can be removed.