3
7 8 1 6 9 2 5 4 3
解析:个人认为是道比较经典的模拟题,很考察基本功,今天又拿来做了一下,方法就是模拟每个方向的坐标变化即可,顺便推荐本书,感觉刘汝佳的《算法竞赛入门经典》很适合入门的人来看哈!
贴一下自己的代码
#include <iostream>
using std::endl;
using std::cin;
using std::cout;
const int MAXN = 100 +10;
int data[MAXN][MAXN];
int main()
{
#ifdef LOCAL
freopen("input.txt" , "r" , stdin);
freopen("output.txt" , "w" , stdout);
#endif
int n;
while(cin >> n)
{
memset(data,0,sizeof(data));
int x=0 , y = n-1 , cnt = 1;
data[x][y] = cnt;
while(cnt < n*n)
{
//向下走
while(x+1<n && !data[x+1][y])
{
data[++x][y] = ++cnt;
}
//向左走
while(y-1>=0 && !data[x][y-1])
{
data[x][--y] = ++cnt;
}
//向上走
while(x-1 >=0 && !data[x-1][y])
{
data[--x][y] = ++cnt;
}
//向右走
while(y+1 <n && !data[x][y+1])
{
data[x][++y] = ++cnt;
}
}
for(int i=0; i<n; ++i)
{
for(int j=0; j<n; ++j)
{
cout << data[i][j] << " ";
}
cout << endl;
}
}
return 0;
}1 2 3 4 5 12 13 14 6 11 15 7 10 8 9跟蛇形填数一样,只是填数要求按照三角形填。注意每组数据之间用空行隔开
2 5 4
1 2 3 4 5 12 13 14 6 11 15 7 10 8 9 1 2 3 4 9 10 5 8 6 7
解析:蛇形填数的变形,三角填数,本质还是模拟数字填充的方法即可哈!
贴一下自己的代码
#include <iostream>
#include <string.h>
using std::endl;
using std::cin;
using std::cout;
const int MAXN = 1000 + 10;
int data[MAXN][MAXN];
int main()
{
int n;
#ifdef LOCAL
freopen("input.txt" , "r" , stdin);
freopen("output.txt" , "w" , stdout);
#endif
cin >> n;
while(n--)
{
memset(data , 0 , sizeof(data));
int length;
cin >> length;
int x=0 , y=0 , cnt = 1;
data[x][y] = cnt;
while(cnt < ((length+1)*length)/2)
{
//向右走
while(y+1 < length-x && !data[x][y+1])
{
data[x][++y] = ++cnt;
}
//向对角线走
while(x+1 < length && y-1>=0 && !data[x+1][y-1])
{
data[++x][--y] = ++cnt;
}
//向上走
while(x-1>=0 && !data[x-1][y])
{
data[--x][y] = ++cnt;
}
}
//输出
for(int i=0; i<length; ++i)
{
for(int j=0; j<length - i; ++j)
{
cout << data[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}NYOJ---蛇形填数(方块填数+三角填数),布布扣,bubuko.com
原文地址:http://blog.csdn.net/jsjliuyun/article/details/27965229