54. Spiral Matrix

来源:互联网 发布:vb中名称和caption 编辑:程序博客网 时间:2024/05/22 12:05

Given a matrix of 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 should return [1,2,3,6,9,8,7,4,5].

旋转打印矩阵。思路如下:1、先从左往右打印(没有条件限制);2、打印矩阵的右边界(需满足矩阵的列数大于1,否则会有1重叠);3、打印矩阵的下边界(需满足矩阵的行数大于1,否则会与1重叠);3、答应矩阵的左边界(需满足列数大于1,否则与1重叠)。

程序如下:

class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        int rowMin = 0, rowMax = matrix.length, colMin = 0;        if (matrix == null||rowMax == 0){            return new ArrayList<Integer>();        }        int colMax = matrix[0].length;         List<Integer> lst = new ArrayList<>();        if (colMax == 0){            return lst;        }        while (rowMin < rowMax&&colMin < colMax){            for (int i = colMin; i < colMax; ++ i){                lst.add(matrix[rowMin][i]);            }            for (int i = rowMin + 1; colMax >= 1&&i < rowMax; ++ i){                lst.add(matrix[i][colMax-1]);            }            for (int i = colMax - 2; rowMax - rowMin > 1&&i >= colMin; -- i){                lst.add(matrix[rowMax-1][i]);            }            for (int i = rowMax - 2; colMax - colMin > 1&&i > rowMin; -- i){                lst.add(matrix[i][colMin]);            }            rowMin ++;            rowMax --;            colMin ++;            colMax --;        }        return lst;    }}