题目描述
以1为中心,用2,3,4, ..., n, ..., n*n的数字围绕着中心输出数圈, 如若n=4,则
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13
输入
一个整数n(1<=n<=10)
输出
数圈矩阵
样例输入
5
样例输出
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
我个人的想法是先确定最后一个数字,然后再逆时针填充。但是不知道如何实现,求各位大神帮帮忙
#include <iostream>
using namespace std;
int a[1000][1000];
int c;
int dire;
int x, y;
int n;
int i, j;
void move()
{
switch (dire)
{
case 0:
x++; return;
case 1:
y++; return;
case 2:
x--; return;
case 3:
y--; return;
}
}
int main()
{
cin >> n;
x = (n - 1) / 2;
y = x;
c = 1;
a[y][x] = c;
c++;
dire = 0;
move();
a[y][x] = c;
c++;
dire = (dire + 1) % 4;
for (i = 1; i < n; i++)
{
for (j = 0; j < i; j++)
{
move();
a[y][x] = c;
c++;
}
dire = (dire + 1) % 4;
for (j = 0; j < i; j++)
{
move();
a[y][x] = c;
c++;
}
move();
a[y][x] = c;
c++;
dire = (dire + 1) % 4;
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
cout << a[i][j] << ' ';
}
cout << endl;
}
return 0;
}
Right
,Left
,Up
,Down
,若在右上角,逆时针转动方向就是Left
->Down
->Right
->Up
->Left
....;若在左下角,自己推一下;Left
,那就一直column--
然后给矩阵赋值,遇到边界column < 0或者数组当前位置的值!= -1
后, 改变方向为Down
,继续.....#include
#include
int main()
{
int a[3][4]={1,3,5,7,9,11,13,15,17,19,21,23};
int b[5]={1,2,3,4,5};
printf("%d,%d\n",a,*a);//0行首地址和0行0列元素地址
printf("%d,%d\n",b,*b);
printf("%d,%d\n",a[0],(*(a+0)));//0行0......
答案就在这里:二维数组的输出问题
----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。
#include
using namespace std;
int a[1000][1000];
int c;
int dire;
int x, y;
int n;
int i, j;
void move()
{
switch (dire)
{
case 0:
x++; return;
case 1:
y++; return;
case 2:
x--; return;
case 3:
y--; return;
}
}
int main()
{
cin >> n;
x = (n - 1) / 2;
y = x;
c = 1;
a[y][x] = c;
c++;
dire = 0;
move();
a[y][x] = c;
c++;
dire = (dire + 1) % 4;
for (i = 1; i < n; i++)
{
for (j = 0; j < i; j++)
{
move();
a[y][x] = c;
c++;
}
dire = (dire + 1) % 4;
for (j = 0; j < i; j++)
{
move();
a[y][x] = c;
c++;
}
move();
a[y][x] = c;
c++;
dire = (dire + 1) % 4;
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
cout << a[i][j] << ' ';
}
cout << endl;
}
return 0;
}
#include
using namespace std;
int a[1000][1000];
int c;
int dire;
int x, y;
int n;
int i, j;
void move()
{
switch (dire)
{
case 0: //向右走
x++; return;
case 1: //向下走
y++; return;
case 2: //向左走
x--; return;
case 3: //向上走
y--; return;
}
}
int main()
{
cin >> n; //输入n
x = (n - 1) / 2;
y = x; //找出1的位置
c = 1;
a[y][x] = c;
c++;
dire = 0;
move(); //初始化完成
a[y][x] = c; //开始填充
c++;
dire = (dire + 1) % 4; //用于改变方向,方向改变的顺序总是右下左上,分别是0123
for (i = 1; i < n; i++)
{
for (j = 0; j < i; j++)
{
move();
a[y][x] = c;
c++;
}
dire = (dire + 1) % 4; //第一次改变方向
for (j = 0; j < i; j++)
{
move();
a[y][x] = c;
c++;
}
move();
a[y][x] = c;
c++;
dire = (dire + 1) % 4; //第二次改变方向
}
//输出结果
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
cout << a[i][j] << ' ';
}
cout << endl;
}
return 0;
}
从前往后和从后往前难度差不多,从前往后更直观一点
说明看注释,不清楚的地方可以再问