Skip to content

Instantly share code, notes, and snippets.

@cohalz
Created September 24, 2013 04:43
Show Gist options
  • Save cohalz/6680473 to your computer and use it in GitHub Desktop.
Save cohalz/6680473 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define maxRow 99 //最大行数
int main() {
int n,x,y;
int count = 1; //探索している数字。
short **arr,*base_arr; //行列。
printf("n = ");
while(scanf("%d", &n) != 1 || n < 3 || n > maxRow || n%2 == 0) {
printf("#matrix must be at least 3 and at most %d and odd.\n",maxRow);
while(getchar() != '\n') {};
printf("n = ");
}
arr = malloc(sizeof(short *) * n);
base_arr = malloc(sizeof(short) * n * n);
for(y=0;y<n;y++) {
arr[y] = base_arr + y * n;
for(x=0;x<n;x++) {
arr[y][x] = 0;
}
}
y = 0;
x = n/2;
arr[y][x] = 1;
count++;
while(count <= n*n) {
if(count%n == 1) {
y++;
if(y == n) y-= n;
} else {
y--;
x++;
if(x == n) x-= n;
if(y == -1) y+= n;
}
while(arr[y][x] != 0) {
y++;
if(y == n) y-= n;
}
arr[y][x] = count;
count++;
}
for(y=0;y<n;y++) {
for(x=0;x<n;x++) {
printf("%4d",arr[y][x]);
}
puts("");
}
free(base_arr);
free(arr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment