思路:考验思维能力的一道题目,细心即可
public class Solution {
public int[] spiralOrder(int[][] matrix) {
// 行数
int row = matrix.length;
if (row == 0) return new int[]{};
// 列数
int col = matrix[0].length;
// 边界值/限定坐标值
int rightBorder = col - 1;// 小于等于
int downBorder = row - 1;// 小于等于
int leftBorder = 0;//大于等于
int upBorder = 1;//大于等于
int[] res = new int[row * col];//结果
int i = 0;// 遍历的横坐标
int j = -1;//遍历的纵坐标
int count = -1;//结果中的序号数
while (true) {//右下左上遍历
if (j == rightBorder) break;//先向右遍历,如果等于边界值,直接结束
else {//不等于边界值,向右遍历到边界值
while (j < rightBorder) {
count++;
j++;
res[count] = matrix[i][j];
}
rightBorder--;//边界值减一
}
if (i == downBorder) break;
else {
while (i < downBorder) {
count++;
i++;
res[count] = matrix[i][j];
}
downBorder--;
}
if (j == leftBorder) break;
else {
while (j > leftBorder) {
count++;
j--;
res[count] = matrix[i][j];
}
leftBorder++;
}
if (i == upBorder) break;
else {
while (i > upBorder) {
count++;
i--;
res[count] = matrix[i][j];
}
upBorder++;
}
}
return res;
}
}