2014年5月11日星期日

Loop Solution - Spiral Matrix - Matrix

The idea is to loop each edge of the matrix, by tl->tr tr->br br->bl bl->tl. each start from the next to avoid duplicates, and for ladder two need to check if the height and width bigger than 1, to avoid duplicates.  Next start coordinates need to be passed to as the base like 1,1. usage as y + n - 1 (1 + (original n - 2 - 1)) as the new edge position. When m and n reduce to be 0 or smaller than 0, it is time to end the recursion and return.

public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        if(matrix ==null || matrix.length == 0 || matrix[0].length == 0){
            return new ArrayList<Integer>();
        }
     
        ArrayList<Integer> result = new ArrayList<Integer>();
        spiralOrderCollector(matrix, result, matrix.length, matrix[0].length,  0 , 0);
        return result;
    }
 
    private void spiralOrderCollector(int[][] matrix, ArrayList<Integer> result, int m, int n, int x, int y){
        if(m <= 0 || n <= 0){
            return;
        }
 
        int loop = 0;
        while(loop < n){
            result.add(matrix[x][y + loop]);
            loop++;
        }
        loop = 1;
        while(loop < m){
            result.add(matrix[x + loop][y + n - 1]);
            loop++;
        }
        loop = 1;
        while(loop < n && m > 1){
            result.add(matrix[x + m - 1][y + n - 1 - loop]);
            loop++;
        }
        loop = 1;
        while(loop < m - 1 && n > 1){
            result.add(matrix[x + m - 1 - loop][y]);
            loop++;
        }
        spiralOrderCollector(matrix, result, m - 2, n - 2, x + 1, y + 1);
    }
}

没有评论: