数字矩阵(贪吃蛇)
#include <iostream>
using namespace std;
typedef struct
{
int x;
int y;
}Position;
int m[30][30];
Position here,next1;
Position DIR[4] = { 0,1,1,0,0,-1,-1,0 };
void Init(int n)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
m[i][j] = 0;
}
}
for (int j = 0; j <= n + 1; j++)
{
m[0][j] = m[n + 1][j] = -1;
}
for (int i = 0; i <= n; i++)
{
m[i][0] = m[i][n + 1] = -1;
}
}
void Solve(int n)
{
here.x = 1;
here.y = 1;
int dirIndex = 0;
int num = 1;
m[1][1] = 1;
while (num < n * n)
{
next1.x = here.x + DIR[dirIndex].x;
next1.y = here.y + DIR[dirIndex].y;
if (m[next1.x][next1.y] == 0)
{
m[next1.x][next1.y] = ++num;
here = next1;
}
else
dirIndex = (dirIndex + 1) % 4;
}
}
void Print(int start, int endi)
{
for (int i = start; i <= endi; i++)
{
cout << m[i][start];
for (int j = start + 1; j <= endi; j++)
{
cout << "\t" << m[i][j];
}
cout << endl;
}
}
int main()
{
int n = 0;
cout << "请输入大于1小于等于20的整数n:" << endl;
cin >> n;
while (n < 1 || n>20)
{
cout << "请输入大于1小于等于20的整数n:" << endl;
cin >> n;
}
Init(n);
Print(0, n + 1);
Solve(n);
Print(1, n);
return 0;
}