题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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
来源:力扣(LeetCode)链接
题解:
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
//如果matrix为空,就直接返回空的数组
return new int[0];
}
int m = matrix.length;//m表示natrix的行数
int n = matrix[0].length;//n表示natrix的列数
int[] res = new int[m * n];//定义一个一维数组存放结果
int count = 0;//结果数组res的索引
int offset = 1;//每圈每行或每列走的步长为m/n-offset
int startX = 0;//每一圈循环行的起始位置
int startY = 0;//每一圈循环列的起始位置
int i,j;//i,j是matrix的索引下标
if (m == 1) {//说明matrix数组只有一行,直接返回一行
return matrix[0];
}
if (n == 1) {//说明matrix数组只有一列
for (int k = 0; k < m; k++) {
res[k] = matrix[k][0];
}
return res;
}
while (count < m * n) {
i = startX;//把起始下标赋给i和j
j = startY;
if (count == m * n - 1 && m == n && m % 2 == 1) {
//处理奇数矩阵的中间位置,如3x3矩阵的[1][1]位置
int mid = m / 2;
res[count] = matrix[mid][mid];
return res;
}
//填充上行从左到右(左闭右开)
for (; j < n - offset; j++) {
res[count] = matrix[i][j];
count++;
if (count == m * n) {
return res;
}
}
//填充右列从上到下(左闭右开)
for (; i < m - offset; i++) {
res[count] = matrix[i][j];
count++;
if (count == m * n) {
return res;
}
}
//填充下行从右到左(左闭右开)
for (; j > startY; j--) {
res[count] = matrix[i][j];
count++;
if (count == m * n) {
return res;
}
}
//填充左列从下到上(左闭右开)
for (; i > startX; i--) {
res[count] = matrix[i][j];
count++;
if (count == m * n) {
return res;
}
}
//每一圈结束后,起始位置都要加1
startX++;
startY++;
//offset控制每圈中每条边的步长
offset++;
}
return res;
}
}
标签:count,顺时针,return,matrix,Offer,int,res,29,++
From: https://www.cnblogs.com/benben-home/p/17235260.html