D94 733. Flood Fill
Topic link
733. Flood Fill
Subject analysis
Given a two-dimensional table, replace the given element with the specified value. Do the same substitution if the four directions have the same number. And so on.
Train of thought
Starting with the specified element, determine whether the surrounding element has reached the boundary. If yes, determine whether the value is the same as the original value. If so, put it on the to-do list. For example, whether there is an element above it and if so, whether it has the same value as the current position. If they are the same, they are thrown into the list to be processed.
The final code
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]; }}}}Copy the code
If you find this article useful, you are welcome to subsidize it with love.