Leetcode—— 54. Spiral Matrix

题目原址

https://leetcode.com/problems/spiral-matrix/description/

题目描述

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

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

解题思路

该题与LeetCode59——Spiral Matrix II题是一个类型题,该题是希望将给定的数组按照螺旋数组的方式遍历出来,将结果放在List集合中。实际上考察的就是坐标的变换关系。这里判断的终止条件有两个,即两个条件满足其中一个就表示已经遍历完所有的元素了。条件为:left + right == matrix[0].lengthtop + bottom == matrix.length

AC代码

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<Integer>();
        if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0)
            return list;
        int row = matrix.length, line = matrix[0].length;
        int top = 0, bottom = 0, left = 0, right = 0;
        while(true) {
            //上边
            for(int i = left; i < line - right; i++){
                list.add(matrix[top][i]);
            }
            top ++;
            if(top + bottom == row)
                break;

            //右边
            for(int i = top; i < row - bottom; i++) {
                list.add(matrix[i][line - 1 - right]);
            }
            right ++;
            if(right + left == line)
                break;

            //下边
            for(int i = line - 1 - right; i >= left; i--) {
                list.add(matrix[row - 1 - bottom][i]);
            }
            bottom ++;
            if(bottom + top == row)
                break;

            //左边
            for(int i = row - 1 - bottom; i >= top; i--) {
                list.add(matrix[i][left]);
            }
            left ++;
            if(left + right == line)
                break;

        }
        return list;        
    }
}

猜你喜欢

转载自blog.csdn.net/xiaojie_570/article/details/80321448