Tuesday, February 4, 2014

Leetcode: 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) {
        List<Integer> solution = new ArrayList<Integer>();
        if(matrix.length==0 || matrix[0].length==0)
            return solution;
        int beginRow = 0;
        int endRow = matrix.length-1;
        int beginCol = 0;
        int endCol = matrix[0].length-1;
        int actualRow = 0;
        int actualCol = 0;
        int state = actualCol == endCol ? 1 : 0;
        while(solution.size()<matrix.length * matrix[0].length)
        {
            solution.add(matrix[actualRow][actualCol]);
            switch(state)
            {
            case 0:
                actualCol++;
                if (actualCol == endCol)
                {
                    state++;
                    beginRow++;
                }   
                break;
            case 1:
                actualRow ++;
                if (actualRow== endRow)
                {
                    state++;
                    endCol--;
                }
                break;
            case 2:
                actualCol--;
                if (actualCol == beginCol)
                {
                    state++;
                    endRow--;
                }
                break;
            case 3:
                actualRow --;
                if (actualRow == beginRow)
                {
                    state = 0;
                    beginCol++;
                }
            }
        }
        return solution;
    }
}

No comments :

Post a Comment