Tuesday, April 26, 2016

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


public class Solution {
    
    public List spiralOrder(int[][] matrix) {
        
        List res = new ArrayList();
        
        int m = matrix.length;
        if(0 == m)
            return res;
            
        int n = matrix[0].length;
        if(0 == n)
            return res;
            
        int i = 0; 
        int j = 0;
        
        while( m > 1 && n > 1){
            for(int k = 0; k < n -1; k++){
                res.add(matrix[i][j++]);
            }
            for(int k = 0; k < m -1; k++){
                res.add(matrix[i++][j]);
            }
            for(int k = 0; k < n -1; k++){
                res.add(matrix[i][j--]);
            }
            for(int k = 0; k < m -1; k++){
                res.add(matrix[i--][j]);
                
            }
            ++i; 
            ++j;
            m -= 2;
            n -= 2;
        }
        
        if(1 == n && 1 == m){
            res.add(matrix[i][j]);
        }
        
        if(m > 1 && 1 == n){
            for(int k = 0; k < m; ++k){
                res.add(matrix[i++][j]);
            }
        }
        if(n > 1 && 1 == m){
            for(int k = 0; k < n; ++k){
                res.add(matrix[i][j++]);
            }
        }
        return res;
            
    }
    
    
}

No comments:

Post a Comment