54. Spiral Matrix

Description

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

Solution

Iteration, time O(m*n), space O(1)

注意边界条件即可。

class Solution {
    public List spiralOrder(int[][] matrix) {
        List list = new LinkedList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return list;
        }
        
        int m = matrix.length;
        int n = matrix[0].length;
        
        for (int i = 0; i < (Math.min(m, n) + 1) / 2; ++i) {
            // Traverse right
            for (int j = i; j < n - i; ++j) {
                list.add(matrix[i][j]);
            }
            
            if (i == m - i - 1) {   // only one row
                continue;
            }
            
            // Traverse down
            for (int j = i + 1; j < m - i - 1; ++j) {
                list.add(matrix[j][n - i - 1]);
            }
            // Traverse left
            for (int j = n - i - 1; j >= i; --j) {
                list.add(matrix[m - i - 1][j]);
            }
            
            if (i == n - i - 1) {   // only one col
                continue;
            }
            // Traverse up
            for (int j = m - i - 2; j > i; --j) {
                list.add(matrix[j][i]);
            }
        }
        
        return list;
    }
}

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