Spiral Matrix

    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<Integer> result = new ArrayList<Integer>();
        int m = matrix.length;
        if(m == 0) return result;
        int n = matrix[0].length;
        return spiralOrder(matrix, 0, 0, m, n);
    }
    
    public ArrayList<Integer> spiralOrder(int[][] matrix, int row, int column, int rLength, int cLength) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(rLength <= 0 || cLength <= 0) return result;
        if(rLength == 1) {
            for(int i = column; i < cLength + column; i++) {
                result.add(matrix[row][i]);
            }
            return result;
        }else if(cLength == 1) {
            for(int i = row; i < rLength + row; i++) {
                result.add(matrix[i][column]);
            }
            return result;
        }else{
            for(int i = column; i < cLength + column - 1; i++) {
                result.add(matrix[row][i]);
            }
            for(int i = row; i < rLength + row - 1; i++) {
                result.add(matrix[i][cLength + column - 1]);
            }
            for(int i = column; i < cLength + column - 1; i++) {
                result.add(matrix[rLength + row - 1][cLength + 2 * column - 1 - i]);
            }
            for(int i = row; i < rLength + row - 1; i++) {
                result.add(matrix[rLength + 2 * row - 1 - i][column]);
            }
        }
        result.addAll(spiralOrder(matrix, row + 1, column + 1, rLength - 2, cLength - 2));
        return result;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章