这道题有点超出我能力范围。。。请各位大神帮帮忙!
1169: 蛇形矩阵时间限制: 1 Sec 内存限制: 0 MB
提交: 102 解决: 50
[提交][题解][状态][讨论版]
题目描述
小明玩一个数字游戏,取个n行n列数字矩阵(其中n为不超过100的奇数),数字的填补方法为:在矩阵中心从1开始以逆时针方向绕行,逐圈扩大,直到n行n列填满数字.
输入
n(即n行n列)
输出
n+1行,n行为组成的矩阵
样例输入
3
样例输出
5 4 3
6 1 2
7 8 9
#include<stdio.h> int map[100][100]; int main() { int way[4][2]={{0,1},{-1,0},{0,-1},{1,0}}; int n; scanf("%d",&n); int x,y,n_way=0,i=1,j; int k1=0,k2=1,k3=0; x=n/2,y=n/2; while(x+y!=2*(n-1)){ map[x][y]=i; i++; x+=way[n_way][0]; y+=way[n_way][1]; k1++; if(k1==k2){ k1=0; k3++; n_way++; n_way%=4; } if(k3==2){ k2++; k3=0; } } map[x][y]=i; for(i=0;i<n;i++){ for(j=0;j<n;j++){ printf("%d ",map[i][j]); } printf("\n"); } return 0; }
#include <stdio.h> #define LENTH 100 void write(unsigned[][LENTH], size_t); void print(unsigned[][LENTH], size_t); int main(void) { unsigned a[LENTH][LENTH]; unsigned n; while (scanf("%u", &n)) { write(a, n); print(a, n); printf("\n"); } return 0; } void write(unsigned a[][LENTH], size_t n) { unsigned num = n * n; unsigned lap = 0; size_t i = n - 1, j = n; while (lap < n / 2 + 1) { while (j > lap) a[i][--j] = num--; while (i > lap) a[--i][j] = num--; while (j + lap + 1< n) a[i][++j] = num--; while (i + lap + 2 < n) a[++i][j] = num--; lap++; } } void print(unsigned a[][LENTH], size_t n) { for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < n; j++) printf("%5u", a[i][j]); printf("\n"); } }