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) {
        //the return list 
        List<Integer> ret = new ArrayList<Integer> (); 
        int row = matrix.length; 
        if (matrix.length == 0) return ret; 
        int col = matrix[0].length; 
        recursion(matrix, ret, 0, 0, row-1, col-1);
        return ret;
    }
    public void recursion(int[][] matrix, List<Integer> ret, int x1, int y1, int x2, int y2) {
        int m  = x2 - x1 + 1; 
        //(x1, y1) must be smaller than (x2, y2)
        if (x1 > x2 || y1 > y2)  return; 
        //empty 
        if (m <= 0) return; 
        //single row
        if (m == 1) {
            for (int j = y1; j <= y2; j++) {
                ret.add(matrix[x1][j]);
            }
            return; 
        }
        //multiples rows: 
        int n = y2 - y1 + 1; 
        //single column
        if (n == 1) {
            for (int i = x1; i <= x2; i++) {
                ret.add(matrix[i][y1]);
            }
            return; 
        }
        //add the first row
        for (int j = y1; j < y2; j++) {
            ret.add(matrix[x1][j]);
        }
        //add the last col 
        for (int i = x1; i < x2; i++) {
            ret.add(matrix[i][y2]);
        }
        //add the last row 
        for (int j = y2; j > y1; j--) {
            ret.add(matrix[x2][j]);
        }
        //add the first col
        for (int i = x2; i > x1; i--) {
            ret.add(matrix[i][y1]);
        }
        //shrink boundary
        recursion(matrix, ret, x1+1, y1+1, x2-1, y2-1);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s