牛客OJ:把正方形矩阵按顺时针输出
程序员文章站
2022-04-02 18:29:21
...
#include <bits/stdc++.h>
using namespace std;
vector<int> printMatrix(vector<vector<int> > matrix) {
if(matrix.size()<=0) return *(new vector<int>);
// right , down, left , up;
const int dirX[] = {0,1,0,-1};
const int dirY[] = {1,0,-1,0};
vector<int> ans;
int locX = 0;
int locY = 0;
int cnt = 0;
int L = matrix.size() - 1;
ans.resize(matrix.size()*matrix.size());
while(L>0){
for(int i=0;i<4;i++){
for(int j=0;j<L;j++){
ans[cnt++] = matrix[locX][locY];
locX += dirX[i];
locY += dirY[i];
}
}
locX += dirX[1];
locY += dirY[0];
L-=2;
}
if(L==0) ans[cnt++] = matrix[locX][locY];
return ans;
}
int main(){
int base = 5;
vector<vector<int> > v;
for(int i=0;i<base;i++){
vector<int> t;
for(int j=1;j<=base;j++){
t.push_back(i*base+j);
}
v.push_back(t);
}
vector<int> fuck = printMatrix(v);
for(int i=0;i<fuck.size();i++)
printf("%d ",fuck[i]);
printf("\n");
return 0;
}
推荐阅读