54. Spiral Matrix

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

一刷
题解:
转圈打印矩阵,需要设置left, right, top和bot四个变量来控制, 注意每次增加行/列前要判断list所含元素是否小于矩阵的总元素数目。用边界来控制,if条件中需要加入4个边界。

Time Complexity - O(mn), Space Complexity - O(1)

public class Solution {
    public List spiralOrder(int[][] matrix) {
        List res = new ArrayList<>();
        if(matrix == null || matrix.length == 0) return res;
        int n = matrix.length, m = matrix[0].length;
        int top = 0, bottom = n-1, left = 0, right = m-1;
        int total = n*m;
        while(total>0){
            for(int i=left; i<=right; i++){
                res.add(matrix[top][i]);
                total--;
            }
            top++;
            
            if(total>0){
                for(int i=top; i<=bottom; i++){
                    res.add(matrix[i][right]);
                    total--;
                }
                right--;
            }
            
             if(total>0){
                for(int i=right; i>=left; i--){
                    res.add(matrix[bottom][i]);
                    total--;
                }
                bottom--;
            }
            
             if(total>0){
                for(int i=bottom; i>=top; i--){
                    res.add(matrix[i][left]);
                    total--;
                }
                left++;
            }
        }
        
        return res;
    }
}

你可能感兴趣的:(54. Spiral Matrix)