蛇形填数:在n*n的方阵里填入1,2,3,…,n*n,要求添成蛇形。其中n<=8。例如n=4时的方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
自己写的代码:
有点麻烦
#include<iostream>
using namespace std;
#define MAX 10
int snake[MAX][MAX];
int headx;
int heady;
void refresh(char &d, int n){
if((headx+1 >= n || snake[headx+1][heady] != 0) && d == 'D')
d = 'L';
else if((heady-1 <= 0 || snake[headx][heady-1] != 0) && d == 'L')
d = 'U';
else if((headx-1 <= 0 || snake[headx-1][heady] != 0) && d == 'U')
d = 'R';
else if((snake[headx][heady+1] != 0) && d == 'R')
d = 'D';
}
int main(){
int n;
cin >> n;
//二维数组初始化为0
for(int i = 0;i < n; i++){
for(int j = 0; j < n; j++){
snake[i][j] = 0;
}
}
int num = n*n;
headx = 0;
heady = n-1;
int value = 1;
char direction = 'D';
//根据方向指示移动
while(num--){
snake[headx][heady] = value++;
int x = headx;
int y = heady;
switch(direction){
case 'D': headx++; break;
case 'L': heady--; break;
case 'U': headx--; break;
case 'R': heady++; break;
}
if(snake[headx][heady] != 0 || headx >= n || heady >= n || headx < 0 || heady < 0){
headx = x;
heady = y;
refresh(direction ,n);
switch(direction){
case 'D': headx++; break;
case 'L': heady--; break;
case 'U': headx--; break;
case 'R': heady++; break;
}
}
cout << direction;
}
cout << endl;
for(int i = 0;i < n; i++){
for(int j = 0; j < n; j++){
cout.width(3);
cout.setf(ios::right);
cout << snake[i][j];
}
cout << endl;
}
}
书上给出的算法:
#include<iostream>
#include<string.h>
using namespace std;
#define MAXN 10
int a[MAXN][MAXN];
int main(){
int n;
cin >> n;
int tot = 1;
memset(a,0,sizeof(a));
int x = 0;
int y = n-1;
a[x][y] = tot;
while(tot < n*n){
while(x + 1 < n && !a[x+1][y] ) a[++x][y] = ++tot;
while(y - 1 >= 0 && !a[x][y-1] ) a[x][--y] = ++tot;
while(x - 1 >= 0 && !a[x-1][y] ) a[--x][y] = ++tot;
while(y + 1 > 0 && !a[x][y+1] ) a[x][++y] = ++tot;
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cout.width(3);
cout.setf(ios::right);
cout << a[i][j];
}
cout << endl;
}
}