leetcode-54 Spiral Matrix 顺时针打印矩阵(《剑指offer》面试题20)

问题描述:

Given a matrixof m x n elements (m rows, n columns),return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[

 [ 1,2, 3 ],

 [ 4,5, 6 ],

 [ 7,8, 9 ]

]

You shouldreturn [1,2,3,6,9,8,7,4,5].

 

问题分析:

显然遍历的方向为先向右遍历,再向下遍历,再向左遍历,最后往上遍历;然后循环往复;其中最终的是判断终止的位置;

使用left,right,top,bottom来分别记录当前未遍历数据块的最左端,最右端,最上端,最下端左边;倘若发生left>right或者top>bottom情况,则表示遍历结束;

而以向右遍历为例,向右遍历了整行之后,该行已经遍历完,则未遍历的数据块top端需要下一一位,即top++;此时有可能发生的情况时top++后,超过了bottom,则此时遍历结束;

 

代码:

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();

        if ((matrix == null) || (matrix.length == 0) || (matrix[0].length == 0))
            return result;

        int left = 0; int right = matrix[0].length - 1;
        int top = 0;  int bottom = matrix.length - 1;

        while (true) {
            // ==== 先向右遍历 ===== //
            for (int j = left; j <= right; j++)
                result.add(matrix[top][j]);
            top++; // 遍历后要注意更新四个维度的值
            // 判断是否还需要继续遍历
            if (top > bottom) break;

            // ===== 向下遍历 ===== //
            for (int i = top; i <= bottom; i++)
                result.add(matrix[i][right]);
            right--;
            if (left > right) break;

            // ===== 向左遍历 ===== //
            for (int j = right; j >= left; j--)
                result.add(matrix[bottom][j]);
            bottom--;
            if (top > bottom) break;

            // ===== 向上遍历 ===== //
            for (int i = bottom; i >= top; i--)
                result.add(matrix[i][left]);
            left++;
            if (left > right) break;
        }
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值