LeetCode #73: Set Matrix Zeroes

class Solution {

    /**
     * @param Integer[][] $matrix
     * @return NULL
     */
    function setZeroes(&$matrix) {
        $rowsToZeroOut = [];
        $colsToZeroOut = [];
        for ($i=0; $i<count($matrix); $i++) {
            for ($j=0; $j<count($matrix[$i]); $j++) {
                if ($matrix[$i][$j] === 0) {
                    $rowsToZeroOut[] = $i;
                    $colsToZeroOut[] = $j;
                }
            }
        }
        
        foreach($rowsToZeroOut as $r) {
            for($i=0; $i<count($matrix[$r]); $i++) {
               $matrix[$r][$i] = 0; 
            }
        }
                
        foreach($colsToZeroOut as $c) {
            for($i=0; $i<count($matrix); $i++) {
               $matrix[$i][$c] = 0; 
            }
        }
    }
}

Results:

Runtime: 52 ms, faster than 13.33% of PHP online submissions for Set Matrix Zeroes. Memory Usage: 19.8 MB, less than 80.00% of PHP online submissions for Set Matrix Zeroes.

Leave a Reply

Your email address will not be published. Required fields are marked *