给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针螺旋排列的 n x n 正方形矩阵。
#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
#include <sstream>
#include<set>
using namespace std;
#define maxsize 100
//正方形
vector<vector<int>> kl(int n) {
vector<vector<int>> m(n,vector<int>(n,0));
int s = 0;
int x = n - 1;
int z = 0;
int y = n - 1;
int co = 1;
while (s <= x && z <= y) {
for (int i = z; i <= y; i++) {
m[s][i]=(co++);
}
s += 1;
for (int i = s; i <= x; i++) {
m[i][y]=(co++);
}
y -= 1;
for (int i = y; i >= z; i--) {
m[x][i]=(co++);
}
x -= 1;
for (int i = x; i >= s; i--) {
m[i][z] = (co++);
}
z += 1;
}
return m;
}
int main() {
int n = 3;
vector<vector<int>> m = kl(n);
for (auto a : m) {
for (auto b : a) {
cout << b << " ";
}
cout << endl;
}
return 0;
}
/*123
* 894
* 765
* 上,下,左,右
* for(int i=Z;i<=Y;i++){
* S+=1;
* for(i=s;i<=X;i++){
* Y-=1;
* for(i=y;i>=Z;i--){
* X-=1;
* for(i=x;i>=S;i--){
* Z+=1;
*/
//矩形m*n,加上两条判断语句
vector<vector<int>> generateMatrix(int rows, int cols) {
vector<vector<int>> matrix(rows, vector<int>(cols, 0));
int top = 0, bottom = rows - 1, left = 0, right = cols - 1;
int num = 1;
while (top <= bottom && left <= right) {
// 从左到右
for (int i = left; i <= right; ++i)
matrix[top][i] = num++;
++top;
// 从上到下
for (int i = top; i <= bottom; ++i)
matrix[i][right] = num++;
--right;
// 从右到左
if (top <= bottom) {
for (int i = right; i >= left; --i)
matrix[bottom][i] = num++;
--bottom;
}
// 从下到上
if (left <= right) {
for (int i = bottom; i >= top; --i)
matrix[i][left] = num++;
++left;
}
}
return matrix;
}