剑指 Offer 29. 顺时针打印矩阵

剑指 Offer 29. 顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

代码如下:

class Solution {
    /**
     * @param Integer[][] $matrix
     * @return Integer[]
     */
    function spiralOrder($matrix) {
        // 计算出行和列数
        $row = count($matrix);
        $col = count($matrix[0]);
        // 行列为0,则认为一维
        if($row == 0 || $col == 0){
            return $matrix;
        }
        // 定义新数组
        $result = [];
        // 定义开始方向
        $left = 0;
        $right = $col - 1;
        $top = 0;
        $bottom = $row - 1;
        var_dump($left ,$right, $top, $bottom);
        while($left <= $right && $top <= $bottom){
            for ($i = $left; $i <= $right; ++$i) {
                array_push($result, $matrix[$top][$i]);
            }
            for ($i = $top + 1; $i <= $bottom; ++$i) {
                array_push($result, $matrix[$i][$right]);
            }
            if ($top != $bottom){
                for ($i = $right-1; $i >= $left; --$i) {
                    array_push($result, $matrix[$bottom][$i]);
                }
            }
            if($left != $right){
                for($i = $bottom - 1; $i > $top; --$i) {
                    array_push($result, $matrix[$i][$left]);
                }
            }
            $left++;
            $right--;
            $top++;
            $bottom--;
        }
        return $result;
    }
}

本文链接:http://itarvin.com/detail-120.aspx

登录或者注册以便发表评论

登录

注册