Spiral Matrix

Source

Given a matrix of m x n elements (m rows, n columns), return all elements of 
the matrix in spiral order.

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

Java

public class Solution {
    /**
     * @param matrix a matrix of m x n elements
     * @return an integer list
     */
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<Integer>();
        if(matrix==null || matrix.length==0 || matrix[0].length==0) return result;

        int rowBegin = 0;
        int rowEnd = matrix.length - 1; 

        int colBegin = 0;
        int colEnd = matrix[0].length - 1;  


        while (true) {  
            // From left to right  
            for (int i = colBegin; i <= colEnd; ++i)  
                result.add(matrix[rowBegin][i]);  
            if (++rowBegin > rowEnd) break;  

            // From top down  
            for (int i = rowBegin; i <= rowEnd; ++i)  
                result.add(matrix[i][colEnd]);  
            if (colBegin > --colEnd) break;  

            // From right to left  
            for (int i = colEnd; i >= colBegin; --i)  
                result.add(matrix[rowEnd][i]);  
            if (rowBegin > --rowEnd) break;  

            // From bottom up  
            for (int i = rowEnd; i >= rowBegin; --i)  
                result.add(matrix[i][colBegin]);  
            if (++colBegin > colEnd) break;  
        }  
        return result; 
    }
}