当前位置:网站首页>LeetCode-54
LeetCode-54
2022-07-05 06:17:00 【GreedySnaker】
To give you one m That's ok n Columns of the matrix matrix , Please follow Clockwise spiral sequence , Returns all elements in the matrix .

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector <int> ans;
if (matrix.empty())
{
return ans; // If it is empty , Go straight back to
}
int up = 0; // Upper, lower, left and right boundaries
int down = matrix.size() - 1;
int left = 0;
int right = matrix[0].size() - 1;
while (true)
{
for (int i = left; i <= right; ++i)
{
// towards the right
ans.push_back(matrix[up][i]);
}
if (++up > down)/// Reset the upper boundary , If the upper boundary is greater than the lower boundary , Then the traversal is completed , The same below
{
break;
}
for (int i = up; i <= down; ++i)
{
// Down
ans.push_back(matrix[i][right]);
}
if (--right < left) // Reset the boundary
{
break;
}
for (int i = right; i >= left; --i)
{
// towards the left
ans.push_back(matrix[down][i]);
}
if (--down < up)// Reset the lower boundary
{
break;
}
for (int i = down; i >= up; --i)
{
// Up
ans.push_back(matrix[i][left]);
}
if (++left > right)// Reset the left boundary
{
break;
}
}
return ans;
}
};
Direct loop add array , At present, we can consider whether to add row arrays directly , Don't cycle
边栏推荐
猜你喜欢

MySQL怎么运行的系列(八)14张图说明白MySQL事务原子性和undo日志原理

【LeetCode】Easy | 20. Valid parentheses

LeetCode 0107.二叉树的层序遍历II - 另一种方法

Data visualization chart summary (II)

SPI 详解

Open source storage is so popular, why do we insist on self-development?

1.14 - 流水线

MIT-6874-Deep Learning in the Life Sciences Week 7

Leetcode array operation

leetcode-6111:螺旋矩阵 IV
随机推荐
1041 Be Unique
Leetcode-6111: spiral matrix IV
SPI 详解
Leetcode dynamic programming
开源存储这么香,为何我们还要坚持自研?
LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树
MySQL advanced part 2: MySQL architecture
Leetcode-6109: number of people who know secrets
Règlement sur la sécurité des réseaux dans les écoles professionnelles secondaires du concours de compétences des écoles professionnelles de la province de Guizhou en 2022
多屏电脑截屏会把多屏连着截下来,而不是只截当前屏
The connection and solution between the shortest Hamilton path and the traveling salesman problem
Collection: programming related websites and books
QT判断界面当前点击的按钮和当前鼠标坐标
Daily question 1189 Maximum number of "balloons"
MySQL advanced part 1: index
Open source storage is so popular, why do we insist on self-development?
做 SQL 性能优化真是让人干瞪眼
A reason that is easy to be ignored when the printer is offline
leetcode-6109:知道秘密的人数
剑指 Offer II 058:日程表