标签:二维矩阵 顺序 pre 示例 ref strong 顺时针 str ret
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
1.vector size()
matrix.size()表示二维矩阵有几行。
matrix[0].size()表示二维矩阵有几列。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector <int> ret;
if (matrix.empty()) return ret;
int up = 0, down = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
while (1){
for (int i = left; i <= right; i++){
ret.push_back(matrix[up][i]);
}
if (++up > down) break;
for (int i = up; i <= down; i++){
ret.push_back(matrix[i][right]);
}
if (--right < left) break;
for (int i = right; i >= left; i--){
ret.push_back(matrix[down][i]);
}
if (--down < up) break;
for (int i = down; i>= up; i--){
ret.push_back(matrix[i][left]);
}
if (++left > right) break;
}
return ret;
}
};
标签:二维矩阵 顺序 pre 示例 ref strong 顺时针 str ret
原文地址:https://www.cnblogs.com/xgbt/p/13053096.html