題目:
輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字。
示例 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) {
return new int[0];
}
int rows = matrix.length;
if(rows == 0) {
return new int[0];
}
int cols = matrix[0].length;
if(cols == 0) {
return new int[0];
}
//初始化四個頂點的值
int leftTopRow = 0,leftTopCol = 0;
int leftBottomRow = rows - 1, leftBottomCol = 0;
int rightTopRow = 0, rightTopCol = cols - 1;
int rightBottomRow = rows - 1, rightBottomCol = cols - 1;
int num = cols * rows;
int[] res = new int[num];
int n = 0;
while(n < num) {
//左上-》右上
int i = leftTopRow;
int j = leftTopCol;
for(; j < rightTopCol + 1; j ++) {
res[n ++] = matrix[i][j];
}
if(n == num) {
break;
}
//右上-》右下
i = rightTopRow + 1;
j = rightTopCol;
for(; i < rightBottomRow + 1; i ++) {
res[n ++] = matrix[i][j];
}
if(n == num) {
break;
}
//右下-》左下
i = rightBottomRow;
j = rightBottomCol - 1;
for(; j > leftBottomCol - 1; j --) {
res[n ++] = matrix[i][j];
}
if(n == num) {
break;
}
//左下-》右上
i = leftBottomRow - 1;
j = leftBottomCol;
for(; i > leftTopRow; i --) {
res[n ++] = matrix[i][j];
}
if(n == num) {
break;
}
leftTopRow ++;
leftTopCol ++;
leftBottomRow --;
leftBottomCol ++;
rightTopRow ++;
rightTopCol --;
rightBottomRow --;
rightBottomCol --;
}
return res;
}
}