Skip to content

947. Most Stones Removed with Same Row or Column #429

Answered by topugit
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

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++;
        …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Aug 29, 2024
Maintainer Author

@topugit
Comment options

topugit Aug 29, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants