Leetcode PHP题解--D94 733. Flood Fill

栏目: PHP · 发布时间: 5年前

内容简介:给定一个二维表格,将给定的元素换成指定值。并且若上下左右4个方向有相同数字是也做同样的替换操作。如此反复。从指定的元素开始,先判断周围有没有到达边界。若有,则判断数值是否和原值相同。相同则把它存进待处理列表中。例如,上方是否有元素,有的话是否和当前位置值相同。相同则丢进待处理列表中。

D94 733. Flood Fill

题目链接

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];
            }
        }

    }
}

若觉得本文章对你有用,欢迎用 爱发电 资助。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

逆流而上

逆流而上

阿里巴巴集团成长集编委会 / 电子工业出版社 / 2017-11 / 59.00

本书是阿里巴巴集团荣耀背后的技术血泪史。全书通过分享业务运行过程中各个领域发生的典型“踩坑”案例,帮助大家快速提升自我及团队协作,学习到宝贵的处理经验及实践方案,为互联网生产系统的稳定共同努力。从基础架构、中间件、数据库、云计算、大数据等技术领域中不断积累经验,颠覆技术瓶颈,不断创新以适应不断增长的需求。 本书主要面向互联网技术从业人员和在校师生,使读者能够通过此书基本了解阿里在各技术领域的能力,......一起来看看 《逆流而上》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具