leetcode 54.螺旋矩阵
题干
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
题解
转转输出。
遍历矩阵一遍,从左上角开始,先向右,再向下,再向左,再向上,如此循环。
可以发现前三次(右下左)的行宽和列高都和原矩阵一致,而后行宽和列高每次缩减1,模拟即可。
列向量的情况会有溢出的问题,所以特判,算是先天不足
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rowCount = matrix.size();
if(rowCount == 0) return {};
int colCount = matrix[0].size();
vector<int> ans;
if(colCount == 1){
for(auto i : matrix) ans.push_back(i[0]);
return ans;
}
int n = (rowCount--) * (colCount--);
int leftBound = 0,upperBound = 0;
int currentStatus = 0;
int rowIndex = 0,colIndex = 0;
int decFlag = false;
for(int i = 0 ; i < n ; ++i){
//cout<<matrix[rowIndex][colIndex]<<' ';
if(currentStatus == 0){
ans.push_back(matrix[rowIndex][colIndex]);
colIndex++;
if(colIndex >= colCount){
currentStatus = 1;
colIndex = colCount;
if(decFlag) rowCount--;
}
}else if(currentStatus == 1){
ans.push_back(matrix[rowIndex][colIndex]);
rowIndex++;
if(rowIndex >= rowCount){
currentStatus = 2;
rowIndex = rowCount;
if(decFlag) leftBound++;
}
}else if(currentStatus == 2){
ans.push_back(matrix[rowIndex][colIndex]);
colIndex--;
if(colIndex <= leftBound){
currentStatus = 3;
colIndex = leftBound;
decFlag = true;
upperBound++;
}
}else if(currentStatus == 3){
ans.push_back(matrix[rowIndex][colIndex]);
rowIndex--;
//cout<<'*'<<rowIndex<<' '<<upperBound<<endl;
if(rowIndex <= upperBound){
currentStatus = 0;
rowIndex = upperBound;
if(decFlag) colCount--;
}
}
}
return ans;
}
};