947. Most Stones Removed with Same Row or Column #429
-
Topics: On a 2D plane, we place 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 Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can implement the solution using a Depth-First Search (DFS) approach. The idea is to consider stones that are connected by rows or columns as part of the same connected component. Once you find all connected components, the maximum number of stones that can be removed is the total number of stones minus the number of connected components. Let's implement this solution in PHP: 947. Most Stones Removed with Same Row or Column <?php
function removeStones($stones) {
$visited = array();
$n = count($stones);
$numComponents = 0;
for ($i = 0; $i < $n; $i++) {
if (!isset($visited[$i])) {
dfs($i, $stones, $visited);
$numComponents++;
}
}
return $n - $numComponents;
}
function dfs($stoneIndex, &$stones, &$visited) {
$visited[$stoneIndex] = true;
for ($i = 0; $i < count($stones); $i++) {
if (!isset($visited[$i]) && ($stones[$i][0] == $stones[$stoneIndex][0] || $stones[$i][1] == $stones[$stoneIndex][1])) {
dfs($i, $stones, $visited);
}
}
}
// Example usage:
$stones1 = array(
array(0, 0),
array(0, 1),
array(1, 0),
array(1, 2),
array(2, 1),
array(2, 2)
);
echo removeStones($stones1); // Output: 5
$stones2 = array(
array(0, 0),
array(0, 2),
array(1, 1),
array(2, 0),
array(2, 2)
);
echo removeStones($stones2); // Output: 3
$stones3 = array(
array(0, 0)
);
echo removeStones($stones3); // Output: 0
?> Explanation:
Complexity:
This solution should work efficiently within the given constraints. |
Beta Was this translation helpful? Give feedback.
We can implement the solution using a Depth-First Search (DFS) approach. The idea is to consider stones that are connected by rows or columns as part of the same connected component. Once you find all connected components, the maximum number of stones that can be removed is the total number of stones minus the number of connected components.
Let's implement this solution in PHP: 947. Most Stones Removed with Same Row or Column