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

Solution:
public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        if(matrix == null||matrix.length == 0) return new ArrayList<Integer>();
        int n = matrix.length, m = matrix[0].length, n_left = -1, m_left = -1, total = n*m;
        List<Integer> rt = new ArrayList<Integer>();
        int i = 0, j = 0;
        while(rt.size() != total){
            while(j < m) {rt.add(matrix[i][j]);j++;}
            if(rt.size() == total) return rt;
            n_left++; i++; j--;
            while(i < n) {rt.add(matrix[i][j]);i++;}
            m--; j--; i--;
            while(j > m_left) {rt.add(matrix[i][j]); j--;}
            if(rt.size() == total) return rt;
            n--; j++; i--;
            while(i > n_left) {rt.add(matrix[i][j]); i--;}
            m_left++; i++; j++;
        }
        return rt;
    }
}

results matching ""

    No results matching ""