#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> v;
int row=matrix.size();
int col=matrix[0].size();
int a[row][col];
memset(a, 0, sizeof(a));
int tot=0;
int x=0,y=0;
while(tot<row*col){
while(x>=0&&y<col&&!a[x][y]){
a[x][y]=matrix[x][y];
v.push_back(matrix[x][y]);
y++;
tot++;
}
x++;
y--;
while(x<row&&!a[x][y]){
a[x][y]=matrix[x][y];
v.push_back(matrix[x][y]);
x++;
tot++;
}
y--;
x--;
while(y>=0&&!a[x][y]){
a[x][y]=matrix[x][y];
v.push_back(matrix[x][y]);
y--;
tot++;
}
x--;
y++;
while(x>=0&&!a[x][y]){
a[x][y]=matrix[x][y];
v.push_back(matrix[x][y]);
x--;
tot++;
}
x++;
y++;
}
return v;
}
int main()
{
vector<int> v1,v2,v3,v4,v5;
vector<vector<int>> mat;
for(int i=1;i<=4;i++){
v1.push_back(i);
}
for(int i=5;i<=8;i++){
v2.push_back(i);
}
for(int i=9;i<=12;i++){
v3.push_back(i);
}
for(int i=13;i<=16;i++){
v4.push_back(i);
}
mat.push_back(v1);
mat.push_back(v2);
mat.push_back(v3);
mat.push_back(v4);
v5=spiralOrder(mat);
for(int i=0;i<v5.size();i++){
printf("%d ",v5[i]);
}
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> result;
if(matrix.empty()){
return result;
}
int row = matrix.size();
int col = matrix[0].size();
int count = row * col;
int index = 1;
int beginX = 0,endX = row - 1;
int beginY = 0,endY = col - 1;
while(index <= count){
for(int i = beginY;i <= endY;++i){
result.push_back(matrix[beginX][i]);
++index;
}
++beginX;
if(beginX > endX){
break;
}
for(int i = beginX;i <= endX;++i){
result.push_back(matrix[i][endY]);
++index;
}
--endY;
if(endY < beginY){
break;
}
for(int i = endY;i >= beginY;--i){
result.push_back(matrix[endX][i]);
++index;
}
--endX;
if(endX < beginX){
break;
}
for(int i = endX;i >= beginX;--i){
result.push_back(matrix[i][beginY]);
++index;
}
++beginY;
if(beginX > endY){
break;
}
}
return result;
}
};
int main(){
Solution s;
vector<vector<int> > matrix = {{1,2,3},{4,5,6},{7,8,9}};
vector<int> result = s.spiralOrder(matrix);
for(int i = 0;i < result.size();++i){
cout<<result[i]<<" ";
}
cout<<endl;
return 0;
}
————————————————
版权声明:本文为CSDN博主「SunnyYoona」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/SunnyYoona/article/details/43525253