Thursday, January 8, 2015

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<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new LinkedList<Integer>();
        int m = matrix.length;
        
        if (m == 0)
            return result;
            
        int n = matrix[0].length;
        
        int left = 0, right = n-1, top = 0, bottom = m-1;
        
        // Level by level from exterior to interior
        while (left<right && top<bottom)
        {
            for (int i = left; i < right; i++)
                result.add(matrix[top][i]);
                
            for (int i = top; i < bottom; i++)
                result.add(matrix[i][right]);
    
            for (int i = right; i > left; i--)
                result.add(matrix[bottom][i]);
                
            for (int i = bottom; i > top; i--)
                result.add(matrix[i][left]);

            left++;
            right--;
            top++;
            bottom--;
        }
        
        // Only left one row or only one row
        if (top==bottom && left<right)
            for (int i = left; i <= right; i++)
                result.add(matrix[top][i]);
        
        // Only left one column or only one column
        if (left==right && top<bottom)
            for (int i = top; i <= bottom; i++)
                result.add(matrix[i][right]);
        
        // Cube matrix will left center element (including only one element)
        if (m==n && n%2==1)
            result.add(matrix[m/2][n/2]);
            
        return result;
    }
}

No comments:

Post a Comment