๐ ๅๆ Offer 29. ้กบๆถ้ๆๅฐ็ฉ้ต
2022ๅนด10ๆ10ๆฅ
- algorithm
๐ ๅๆ Offer 29. ้กบๆถ้ๆๅฐ็ฉ้ต
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public int[] spiralOrder(int[][] matrix) {
// ๆ่ทฏ๏ผ
// ๅไธชๆนๅ้ๅ
int row = matrix.length;
if(row == 0) {
return new int[0];
}
int col = matrix[0].length;
if(col == 0) {
return new int[0];
}
int top = 0;
int bottom = row - 1;
int left = 0;
int right = col - 1;
int len = row * col;
int[] res = new int[len];
int index = 0;
while(top <= bottom && left <= right) {
// ๅทฆ --> ๅณ
for(int j = left; j <= right; j ++) {
res[index] = matrix[top][j];
index ++;
}
top ++;
// System.out.println(index + " " + top + " " + bottom + " " + left + " " + right);
if(index == len) {
return res;
}
// ไธ --> ไธ
for(int i = top; i <= bottom; i ++) {
res[index] = matrix[i][right];
index ++;
}
right --;
// System.out.println(index + " " + top + " " + bottom + " " + left + " " + right);
if(index == len) {
return res;
}
// ๅณ --> ๅทฆ
for(int j = right; j >= left; j --) {
res[index] = matrix[bottom][j];
index ++;
}
bottom --;
// System.out.println(index + " " + top + " " + bottom + " " + left + " " + right);
if(index == len) {
return res;
}
// ไธ --> ไธ
for(int i = bottom; i >= top; i --) {
res[index] = matrix[i][left];
index ++;
}
left ++;
// System.out.println(index + " " + top + " " + bottom + " " + left + " " + right);
if(index == len) {
return res;
}
}
return res;
}
}