*在n*n方陈里填入1,2,...,n * n,要求填成蛇形。例如n = 4时方陈为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
输入
直接输入方陈的维数,即n的值。(n<=100)
输出
输出结果是蛇形方陈。
样例输入
3
样例输出
7 8 1
6 9 2
5 4 3
*/
----------------------------------------------------------------------------------------------------------------------
->右边
10 11 12 停止向右并向下 1
9 上 16 13 2 ↓向下
8 ↑ 15 14 3
7 6 5 4
←左
-------------------------------------------------------------------------------------------------------------------
//关于蛇形填数的问题的实现
#include <cstdio>
//#define _OJ_
int main(int argc, char const *argv[]) {
#ifndef _OJ_ //ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
int a[100][100];
int i, j, n , cnt;
scanf("%d", &n);
for(i = 0;i < n; i++) {
for(j = 0;j < n; j++) {
a[i][j] = 0;
}
}
i = 0; j = n - 1; cnt = 1; a[i][j] = cnt;
while (cnt < n * n ) {
while(i + 1 < n && a[i + 1][j] == 0) a[++i][j] = ++cnt;
//先判断要走的下一个位置有没有位置 向下走到底(i+1 < n)为止
//最关键的地方就是下一个位置有数值就停留并转向另一个方向
while(j - 1 >= 0 && a[i][j - 1] == 0) a[i][--j] = ++cnt;
//先判断要走的下一个位置有没有位置 向左边走到底(j - 1 >= 0)为止
while(i - 1 >= 0 && a[i - 1][j] == 0) a[--i][j] = ++cnt;
//先判断要走的下一个位置有没有位置 向上走到底(i - 1 >= 0)为止
while(j + 1 < n && a[i][j + 1] == 0) a[i][++j] = ++cnt;
//先判断要走的下一个位置有没有位置 向右边走到底(j+1 < n)为止
}
for(i = 0;i < n; i++) {
for(j = 0;j < n - 1; j++) {
printf("%d ", a[i][j]);
}
printf("%d\n", a[i][n - 1]);
}
return 0;
}
#include <cstdio> //#define _OJ_ int main(int argc, char const *argv[]) { #ifndef _OJ_ //ONLINE_JUDGE freopen("input.txt", "r", stdin); #endif int a[100][100]; int i, j, n , cnt; scanf("%d", &n); for(i = 0;i < n; i++) { for(j = 0;j < n; j++) { a[i][j] = 0; } } i = 0; j = n - 1; cnt = 1; a[i][j] = cnt; while (cnt < n * n ) { while(i + 1 < n && a[i + 1][j] == 0) a[++i][j] = ++cnt; //先判断要走的下一个位置有没有位置 向下走到底(i+1 < n)为止 //最关键的地方就是下一个位置有数值就停留并转向另一个方向 while(j - 1 >= 0 && a[i][j - 1] == 0) a[i][--j] = ++cnt; //先判断要走的下一个位置有没有位置 向左边走到底(j - 1 >= 0)为止 while(i - 1 >= 0 && a[i - 1][j] == 0) a[--i][j] = ++cnt; //先判断要走的下一个位置有没有位置 向上走到底(i - 1 >= 0)为止 while(j + 1 < n && a[i][j + 1] == 0) a[i][++j] = ++cnt; //先判断要走的下一个位置有没有位置 向右边走到底(j+1 < n)为止 } for(i = 0;i < n; i++) { for(j = 0;j < n - 1; j++) { printf("%d ", a[i][j]); } printf("%d\n", a[i][n - 1]); } return 0; }
原文:http://www.cnblogs.com/airfand/p/5008527.html