1. 程式人生 > 其它 >[LeetCode 簡單]劍指 Offer 29. 順時針列印矩陣

[LeetCode 簡單]劍指 Offer 29. 順時針列印矩陣

技術標籤:leetcode

題目描述

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

示例 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 || matrix[0].length == 0) { return new int[0]; } int rows = matrix.length, columns = matrix[0].length; int[] res = new int[rows*columns]; int index =0; int left=0,right=
columns-1,top=0,bottom=rows-1; while(left<=right && top<=bottom){ for(int column=left;column<=right;column++) res[index++] = matrix[top][column]; for(int row=top+1;row<=bottom;row++) res[index++] = matrix[row][right]; if(left<
right && top<bottom){ for(int column=right-1;column>left;column--) res[index++] = matrix[bottom][column]; for(int row=bottom;row>top;row--) res[index++] = matrix[row][left]; } left++;right--;top++;bottom--; } return res; } }