Skip to content

Latest commit

 

History

History
59 lines (49 loc) · 1.71 KB

54.md

File metadata and controls

59 lines (49 loc) · 1.71 KB

✏️Leetcode基础刷题之(54. Spiral Matrix)


. 2019-07-30 吴亲库里 库里的深夜食堂

✏️题目描述

这道题很有意思,给定一个m*n的矩阵,让我们以螺旋的形式返回。


✏️题目实例

****

✏️题目分析

需要搞清楚返回的顺序,然后确定好边界,剩下的就是代码了,四个方向右->下->左->上的顺序,每一次遍历,上下左右各自向中心缩小一层,至于边界说白了就是行列。

✏️最终实现代码

/**
     * @param Integer[][] $matrix
     * @return Integer[]
     */
    function spiralOrder($matrix) {
        if(empty($matrix)){
            return [];
        }
        $res=[];
        $r1=0;
        $r2=count($matrix)-1;
        $c1=0;
        $c2=count($matrix[0])-1;
        while($r1<=$r2 && $c1<=$c2){
            for($c=$c1;$c<=$c2;$c++) array_push($res,$matrix[$r1][$c]);
            for($r=$r1+1;$r<=$r2;$r++) array_push($res,$matrix[$r][$c2]);
            if($r1<$r2 && $c1<$c2){
                for($c=$c2-1;$c>$c1;$c--) array_push($res,$matrix[$r2][$c]);
                for($r=$r2;$r>$r1;$r--)  array_push($res,$matrix[$r][$c1]);
            }
            $r1++;
            $r2--;
            $c1++;
            $c2--;
        }
        return $res;
    }

联系