1. 程式人生 > 實用技巧 >劍指offer_19:順時針列印矩陣

劍指offer_19:順時針列印矩陣

輸入一個矩陣,按照從外向裡以順時針的順序依次打印出每一個數字。

示例 1:
輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]

示例 2:
輸入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
輸出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

1、模擬運算

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length==0) return new int[0];
        int row=matrix.length;
        int col=matrix[0].length;
        int num=row*col;
        int[] res=new int[num];
        boolean[][] flag=new boolean[row][col];
        int[][] gowhere={{0,1},{1,0},{0,-1},{-1,0}};
        int i=0,j=0;
        int index=0;
        for(int k=0;k<num;k++){
            res[k]=matrix[i][j];
            flag[i][j]=true;
            int newi=i+gowhere[index][0],newj=j+gowhere[index][1];
            if(newj>=col||newi>=row||newj<0||newi<0||flag[newi][newj]==true){
                index++;
                index%=4;
            }
            i+=gowhere[index][0];
            j+=gowhere[index][1];
        }
        return res;
    }
}

2、邊界

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length==0) return new int[0];
        int row=matrix.length;
        int col=matrix[0].length;
        int[] res=new int[row*col];
        int left=0,top=0,right=col-1,bottom=row-1;
        int index=0;
        while(left<=right&&top<=bottom){
            for(int j=left;j<=right;j++){
                res[index++]=matrix[top][j];
            }
            for(int i=top+1;i<=bottom;i++){
                res[index++]=matrix[i][right];
            }
            if(top<bottom){
                for(int j=right-1;j>=left;j--){
                    res[index++]=matrix[bottom][j];
                }
            }
            if(left<right){
                for(int i=bottom-1;i>top;i--){
                    res[index++]=matrix[i][left];
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return res;
    }
}