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

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> res = new ArrayList<Integer>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
        int m = matrix.length;
        int n = matrix[0].length;
        int roundNum = Integer.min(m, n) % 2 == 0 ? Integer.min(m, n) / 2 : Integer.min(m, n) / 2 + 1;
        for(int round = 0; round < roundNum; round++) {
            int i = round;
            int j = round;
            while(j < n - round - 1) res.add(matrix[i][j++]);
            while(i < m - round - 1) res.add(matrix[i++][j]);

            if(round == roundNum - 1 && Integer.min(m, n) % 2 != 0) {
                res.add(matrix[i][j]);
                break;
            }

            while(j > round) res.add(matrix[i][j--]);
            while(i > round) res.add(matrix[i--][j]);
        }
        return res;
    }
}

results matching ""

    No results matching ""