LeetCode 200: Number of Islands

May. 3, 2021

I had to watch some YouTube videos for the solution to this problem. I am not sure if this is the best solution though, one day I will revisit it.


  /**
    * @param String[][] $grid
    * @return Integer
    */
    function numIslands($grid) {
        $count = 0;

        for ($i=0; $i < count  ($grid  );   $i++)   {
           for   ($j  =  0;   $j   <count  ($grid  [$i  ]);   $j++)   {
               if   ($grid  [$i  ][$j  ]   ==   &#34;1  &#34;)   {
                     $count++;
                     // zero out rest of 1s
                     $this-  >zeroOut($grid, $i, $j);
                }
            }
        }

        return $count;
    }

    function zeroOut( & $grid, $i, $j) {
        if ($i < 0   ||   $i  >=count($grid) || $j < 0   ||   $j  >=count($grid[$i]) || $grid[$i][$j] == &#34;0&#34;)
            return;

        $grid[$i][$j] = &#34;0&#34;;

        $this- >zeroOut($grid, $i-1, $j);
        $this- >zeroOut($grid, $i+1, $j);
        $this- >zeroOut($grid, $i, $j-1);
        $this- >zeroOut($grid, $i, $j+1);
    }
}