螺旋矩阵
作者:互联网
链接
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素
import java.util.*;
public class Solution {
public int[] SpiralMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int n = matrix.length, m = matrix[0].length;
int[] ret = new int[n * m];
int row1 = 0, col1 = 0, row2 = n - 1, col2 = m - 1;
int index = 0;
while (row1 <= row2 && col1 <= col2) {
if (row1 == row2) {
for (int i = col1; i <= col2; ++i) {
ret[index++] = matrix[row1][i];
}
} else if (col1 == col2) {
for (int i = row1; i <= row2; ++i) {
ret[index++] = matrix[i][col1];
}
} else {
for (int i = col1; i < col2; ++i) {
ret[index++] = matrix[row1][i];
}
for (int i = row1; i < row2; ++i) {
ret[index++] = matrix[i][col2];
}
for (int i = col2; i > col1; --i) {
ret[index++] = matrix[row2][i];
}
for (int i = row2; i > row1; --i) {
ret[index++] = matrix[i][col1];
}
}
row1++;
col1++;
row2--;
col2--;
}
return ret;
}
}
标签:row1,row2,matrix,螺旋,int,矩阵,ret,col1 来源: https://www.cnblogs.com/tianyiya/p/15399872.html