劍指offer 29 順時針打印矩陣

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

示例 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
題解鏈接

代碼

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0) return new int[0];
        int left = 0, right = matrix[0].length-1 , top = 0, bottom = matrix.length-1, x = 0;
        int k = 0;
        int i=0,j=0;
        int[] res = new int[(right+1)*(bottom+1)];
        while(true){
            //from left to right
            if(left > right){
                break;
            }
            for(j=left;j<=right;j++ ){
                res[k++] = matrix[i][j];
            }
            top++;
            j--;
            //from top to bottom
            if(top > bottom){
                break;
            }
            for(i=top;i<=bottom;i++){
                res[k++] = matrix[i][j];
            }
            right--;
            i--;
            //from right to left
            if(left > right){
                break;
            }
            for(j=right;j>=left;j--){
                res[k++] = matrix[i][j];
            }
            bottom--;
            j++;
            //from bottom to top
            if(top > bottom){
                break;
            }
            for(i=bottom;i>=top;i--){
                res[k++] = matrix[i][j];
            }
            left++;
            i++;
        }
        return res;
    }
}

注意: 每行或每列遍歷後除了要改變top,bottom,left,right的值,還要對用來遍歷行和列的i,j值進行改變,因爲當前遍歷結束後i和j的值還會改變一次,而下一次遍歷的i,j值若從改變後的i,j值開始,會超出數組範圍

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