[leedcode 54] 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 {
    //本题面试时考过,解决办法就是画图,注意边界
    List<Integer>  res;
    public List<Integer> spiralOrder(int[][] matrix) {
        res=new ArrayList<Integer>();
        if(matrix==null||matrix.length==0) return res;
        int row=matrix.length;
        int col=matrix[0].length;
        int minRow=0;
        int minCol=0;
        int maxRow=row-1;
        int maxCol=col-1;
        while(maxRow>=minRow&&maxCol>=minCol){
            print(matrix,minRow,maxRow,minCol,maxCol);
            minRow++;
            maxRow--;
            minCol++;
            maxCol--;
        }
        return res;
    }
    public void print(int[][] matrix,int minRow,int maxRow,int minCol,int maxCol){
        if(minCol<=maxCol){
            for(int i=minCol;i<=maxCol;i++){
                res.add(matrix[minRow][i]);
            }
        }
        if(minRow<maxRow){
            for(int i=minRow+1;i<=maxRow;i++){
                res.add(matrix[i][maxCol]);
            }
        }
        if(minCol<maxCol&&minRow<maxRow){
            for(int i=maxCol-1;i>=minCol;i--){
                res.add(matrix[maxRow][i]);
            }
        }
        if(minCol<maxCol&&minRow<maxRow-1){
            for(int i=maxRow-1;i>minRow;i--){
                res.add(matrix[i][minCol]);
            }
        }
        
    }
}

 

你可能感兴趣的:(Matrix)