// IntegerRing.cpp : 定义控制台应用程序的入口点。
//
/*
题目描述
以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 "stdafx.h"
#include <math.h>
int main()
{
int n = 0, c = 0, r = 0;
printf_s("请输入一个整数n(1<=n<=10):\n");
scanf_s("%d", &n);
const int arrLength = n*n;
int* pArr = new int[arrLength];
c = n / 2; //行
r = n / 2; //列
if (n % 2 == 0)
{
--c;
--r;
}
// 1在数组中的位置
int index = r * n + c, preIndex = 0;
pArr[index] = 1;
preIndex = index;
//方向,列走的方向有rgiht、left,行走的方向down、up。
int cRight = 1, rDown = 1, cLeft = -1, rUp = -1;
bool fIsReverse = false, fIsH = true;
if (n > 0 && n < 11)
{
int times = 0 , countTimes = 1;
for (int i = 0; i < arrLength - 1; ++i)
{
++times;
if (fIsH)
{
if (!fIsReverse)
{
c+=cRight;
if (times == countTimes)
{
//改变方向
fIsH = !fIsH;
times = 0;
}
}
else
{
c+=cLeft;
if(times == countTimes)
{
fIsH = !fIsH;
times = 0;
}
}
}
else
{
if (!fIsReverse)
{
r+=rDown;
if (times == countTimes)
{
//改变方向
fIsH = !fIsH;
fIsReverse = !fIsReverse;
times = 0;
++countTimes;
}
}
else
{
r+=rUp;
if (times == countTimes)
{
//改变方向
fIsH = !fIsH;
fIsReverse = !fIsReverse;
times = 0;
++countTimes;
}
}
}
index = r * n + c;
pArr[index] = pArr[preIndex] + 1;
preIndex = index;
}
}
for (int i = 0; i < arrLength; ++i)
{
printf_s("%d ", pArr[i]);
if (i % n == n - 1)
{
printf_s("\n");
}
}
main();
return 0;
}