https://www.acwing.com/problem/content/description/758/
#include<iostream>
#include<cmath>
using namespace std;
int res[100][100];
bool st[100][100];
int main(void)
{
int n,m;
cin>>n>>m;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
for(int x=0,y=0,d=1,k=1;k<=n*m;k++)
{
res[x][y]=k;
st[x][y]=true;//标记填过了
int a=x+dx[d],b=y+dy[d];
if(a<0||a>=n||b<0||b>=m||st[a][b])
{
d=(d+1)%4;
a=x+dx[d],b=y+dy[d];
}
x=a,y=b;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cout<<res[i][j]<<' ';
}
puts("");
}
return 0;
}
容易理解的方式:
利用 left right top bottom 四个变量 来表示 这个矩形的边界。
链接:https://www.acwing.com/solution/content/8007/ 来源:AcWing
#include <iostream>
using namespace std;
const int N = 105;
int a[N][N];
int n, m;
int main() {
cin >> n >> m;
int left = 0, right = m - 1, top = 0, bottom = n - 1;
int k = 1;
while (left <= right && top <= bottom) {
for (int i = left ; i <= right; i ++) {
a[top][i] = k ++;
}
for (int i = top + 1; i <= bottom; i ++) {
a[i][right] = k ++;
}
for (int i = right - 1; i >= left && top < bottom; i --) {
a[bottom][i] = k ++;
}
for (int i = bottom - 1; i > top && left < right; i --) {
a[i][left] = k ++;
}
left ++, right --, top ++, bottom --;
}
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}