leetcode54順時針打印矩陣

leetcode54順時針打印矩陣

題目鏈接順時針打印矩陣

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

示例 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==null||matrix.length==0) return new int[0];
        int[] res = new int[(matrix.length*(matrix[0].length))];
        int rbegin = 0,rend = matrix.length - 1;
        int cbegin = 0,cend = matrix[0].length-1;
        int cnt = 0;
        while(rbegin<=rend&&cbegin<=cend){
              //行不變 列++
              for(int i = cbegin;i<=cend;i++){
                     res[cnt++] = matrix[rbegin][i];
              }
              rbegin++;
              //列不變,行++
              for(int i = rbegin;i<=rend;i++){
                     res[cnt++] = matrix[i][cend];
              }
              cend--;
              //行不變,列--
              if(rbegin<=rend){//循環越界判斷
                 for(int i = cend;i>=cbegin;i--){
                      res[cnt++] = matrix[rend][i];
                 }
                 rend--;
              }
              //列不變,行--
              if(cbegin<=cend){//循環越界判斷
                  for(int i = rend;i>=rbegin;i--){
                       res[cnt++] = matrix[i][cbegin];
                  }
                  cbegin++;
              }
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章