题目链接:54. 螺旋矩阵 - 力扣(LeetCode)
先走外面的圈再走里面的圈,可以用递归来解决,对于要走的一个圈,由四个角决定,其实是三个数,(0,0),(0,n),(m,0),(m,n),每次先从左上角走到右上角,再走到右下角,再走到左下角,再走回来
对于后面两个的往回走要在m和n不等于起点的情况下,否则会重复最后
class Solution {
public:
vector<int> ans;
vector<vector<int> > matrix;
void go(int start, int row, int column) {
if (start > row || start > column)
return;
for (int i = start; i <= column; ++i)
ans.push_back(matrix[start][i]);
for (int i = start + 1; i <= row; ++i)
ans.push_back(matrix[i][column]);
if (row != start)
for (int i = column - 1; i >= start; --i)
ans.push_back(matrix[row][i]);
if (column != start)
for (int i = row - 1; i > start; --i)
ans.push_back(matrix[i][start]);
go(start + 1, row - 1, column - 1);
}
vector<int> spiralOrder(vector<vector<int> > &matrix) {
this->matrix = move(matrix);
go(0, this->matrix.size() - 1, this->matrix[0].size() - 1);
return ans;
}
};
不用递归也可以,改成迭代文章来源:https://www.toymoban.com/news/detail-853377.html
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ans;
int start = 0, row = matrix.size() - 1, column = matrix[0].size() - 1;
while (true) {
if (start > row || start > column)
break;
for (int i = start; i <= column; ++i)
ans.push_back(matrix[start][i]);
for (int i = start + 1; i <= row; ++i)
ans.push_back(matrix[i][column]);
if (row != start)
for (int i = column - 1; i >= start; --i)
ans.push_back(matrix[row][i]);
if (column != start)
for (int i = row - 1; i > start; --i)
ans.push_back(matrix[i][start]);
++start;
--row;
--column;
}
return ans;
}
};
文章来源地址https://www.toymoban.com/news/detail-853377.html
到了这里,关于【LeetCode热题100】【矩阵】螺旋矩阵的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!