【模拟】LeetCode 54. 螺旋矩阵
题目链接
思路
通过维护上下左右四个边界变量来控制循环。
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int firstRow = 0;
int lastColumn = matrix[0].length - 1;
int lastRow = matrix.length - 1;
int firstColumn = 0;
ArrayList<Integer> res = new ArrayList<>();
while(true){
for(int i = firstColumn; i <= lastColumn; ++i){
res.add(matrix[firstRow][i]);
}
if(firstRow + 1 > lastRow){
break;
}
firstRow++;
for(int i = firstRow; i <= lastRow; ++i){
res.add(matrix[i][lastColumn]);
}
if(lastColumn - 1 < firstColumn){
break;
}
lastColumn--;
for(int i = lastColumn; i >= firstColumn; --i){
res.add(matrix[lastRow][i]);
}
if(lastRow - 1 < firstRow){
break;
}
lastRow--;
for(int i = lastRow; i >= firstRow; --i){
res.add(matrix[i][firstColumn]);
}
if(firstColumn + 1 > lastColumn){
break;
}
firstColumn++;
}
return res;
}
}