54. 螺旋矩阵
作者:互联网
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new ArrayList<>();
}
int row1 = 0, col1 = 0, row2 = matrix.length - 1, col2 = matrix[0].length - 1;
List<Integer> ret = new ArrayList<>(matrix.length * matrix[0].length);
while (row1 <= row2 && col1 <= col2) {
if (row1 == row2) {
for (int i = col1; i <= col2; ++i) {
ret.add(matrix[row1][i]);
}
} else if (col1 == col2) {
for (int i = row1; i <= row2; ++i) {
ret.add(matrix[i][col1]);
}
} else {
for (int i = col1; i < col2; ++i) {
ret.add(matrix[row1][i]);
}
for (int i = row1; i < row2; ++i) {
ret.add(matrix[i][col2]);
}
for (int i = col2; i > col1; --i) {
ret.add(matrix[row2][i]);
}
for (int i = row2; i > row1; --i) {
ret.add(matrix[i][col1]);
}
}
row1++;
col1++;
row2--;
col2--;
}
return ret;
}
}
标签:row1,row2,matrix,螺旋,54,矩阵,ret,col1,length 来源: https://www.cnblogs.com/tianyiya/p/15639043.html