54. 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]

题意:

蛇形输出。

思路:

不同于之前的蛇形填数,此题的矩阵可以是长方形的。但可以类比于之前的,设置top,left,right,down四个参数,模拟蛇形进行输出,注意判断截止条件,当top==down||left==right时还可以继续添加,比如3*3的矩阵中,top=down时,num[1][0],num[1][1]尚未添加。所以截止条件是top==down+1||left==right+1.

代码:

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List list=new ArrayList();
        if(matrix.length==0)
            return list;
        int left=0,top=0,right=matrix[0].length-1,down=matrix.length-1;
        int t=0;
        while(left<=right||top<=down)
        {
            for(int i=left;i<=right;i++)
                list.add(matrix[top][i]);
            top++;
            if(top==down+1)
                break;
            for(int i=top;i<=down;i++)
                list.add(matrix[i][right]);
            right--;
            if(left==right+1)
                break;
            for(int i=right;i>=left;i--)
                list.add(matrix[down][i]);
            down--;
            if(top==down+1)
                break;
            for(int i=down;i>=top;i--)
                list.add(matrix[i][left]);
            left++;
            if(left==right+1)
                break;
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36718317/article/details/80028667