面試題29.順時針打印矩陣

面試題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||matrix==null) return new int[0];
        int hs = matrix.length-1;
        int ls = matrix[0].length-1;
        int[] arr = new int[matrix.length*matrix[0].length];
        int h = 0;
        int l = 0;
        int index = 0;
        while(h<=hs&&l<=ls){
        //向右
            for(int i = l;i<=ls;i++){
                arr[index++] = matrix[h][i];
            }
            //向下
            for(int i = h+1;i<=hs;i++){
                arr[index++] = matrix[i][ls];
            }
            向左
            if(h!=hs){
                for(int i = ls-1;i>=l;i--){
                    arr[index++] = matrix[hs][i];
                }
            }
            //向上
            if(l!=ls){
                for(int i = hs-1;i>h;i--){
                    arr[index++] = matrix[i][l];
                }
            }
            h++;
            hs--;
            l++;
            ls--;
        }
        return arr;
    }
}
提交結果

在這裏插入圖片描述

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