leetcode Spiral Matrix题解

题目描述:

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]

Example 2:

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]

中文理解:

给定一个二维矩阵,返回顺时针元素序列。

解题思路:

按层进行输出序列,同时注意特殊情况,矩阵元素为空,在按层打印的时候,注意下边和左边的边界条件,防止对同一行两次输出。

代码(java):

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list=new ArrayList();
        int rows=matrix.length-1;
        if(rows==-1)return list;
        int cols=matrix[0].length-1;
        int startRow=0,startCol=0;
        while(startRow<=rows && startCol<=cols){
            //第一个横行
            int i=0;
            for(i=startCol;i<=cols;i++){
                list.add(matrix[startRow][i]);
            }
            //第一个竖行
            for(i=startRow+1;i<=rows;i++){
                list.add(matrix[i][cols]);
            }
            for(i=cols-1;i>=startCol && startRow!=rows;i--){
                list.add(matrix[rows][i]);
            }
            for(i=rows-1;i>startRow && startCol!=cols;i--){
                list.add(matrix[i][startCol]);
            }
            startRow++;startCol++;rows--;cols--;
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/90167380