Leetcode PHP題解--D94 733. Flood Fill
阿新 • • 發佈:2019-06-28
D94 733. Flood Fill
題目連結
題目分析
給定一個二維表格,將給定的元素換成指定值。並且若上下左右4個方向有相同數字是也做同樣的替換操作。如此反覆。
思路
從指定的元素開始,先判斷周圍有沒有到達邊界。若有,則判斷數值是否和原值相同。相同則把它存進待處理列表中。例如,上方是否有元素,有的話是否和當前位置值相同。相同則丟進待處理列表中。
最終程式碼
<?php class Solution { protected $pendingCell = []; protected $image = []; protected $originalColor = null; /** * @param Integer[][] $image * @param Integer $sr * @param Integer $sc * @param Integer $newColor * @return Integer[][] */ function floodFill($image, $sr, $sc, $newColor) { $this->image = $image; $this->originalColor = $image[$sr][$sc]; $this->pendingCell[] = [$sr, $sc]; while(count($this->pendingCell)){ $point = array_shift($this->pendingCell); $this->fill($point[0], $point[1], $newColor); } return $this->image; } function fill($row, $col, $newColor){ $this->image[$row][$col] = $newColor; if(isset($this->image[$row][$col+1])){ if($this->image[$row][$col+1] == $this->originalColor && $this->image[$row][$col+1] != $newColor){ $this->pendingCell[] = [$row, $col+1]; } } if(isset($this->image[$row][$col-1])){ if($this->image[$row][$col-1] == $this->originalColor && $this->image[$row][$col-1] != $newColor){ $this->pendingCell[] = [$row, $col-1]; } } if(isset($this->image[$row+1][$col])){ if($this->image[$row+1][$col] == $this->originalColor && $this->image[$row+1][$col] != $newColor){ $this->pendingCell[] = [$row+1, $col]; } } if(isset($this->image[$row-1][$col])){ if($this->image[$row-1][$col] == $this->originalColor && $this->image[$row-1][$col] != $newColor){ $this->pendingCell[] = [$row-1, $col]; } } } }