Skip to content

Instantly share code, notes, and snippets.

@cohalz
Created September 24, 2013 04:43
Show Gist options
  • Save cohalz/6680475 to your computer and use it in GitHub Desktop.
Save cohalz/6680475 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define maxRow 15 //最大行数
int main(){
int n; //正方行列の大きさ。
int y = 0;
int x = 0;
int top = 0; //上から数えて何行埋まっているか。文字を右に進みながら入れていき、右端にたどり着けばその行はもう埋まった扱いにする。
int bottom = 0; //同上。
int left = 0; //同上。
int right = 0; //同上。
int count = 0; //文字を入れ終わった回数。
char arr[maxRow][maxRow]; //行列。
char printChar = 'A'; //初期位置の文字。ここをBやZにしても動くように対応。
enum directions { RIGHT,DOWN,LEFT,UP };
enum directions direction = RIGHT;
printf("n = ");
while(scanf("%d", &n) != 1 || n < 3 || n > maxRow) {
printf("#matrix must be at least 3 and at most %d.\n",maxRow);
while(getchar() != '\n') {};
printf("n = ");
}
while(count != n*n) {
arr[y][x] = 'A'+((count+printChar-'A')%26);
count++;
switch(direction) {
case RIGHT:
x++;
if(x == n-1-right) {
direction = DOWN;
top++;
}
break;
case DOWN:
y++;
if(y == n-1-bottom) {
direction = LEFT;
right++;
}
break;
case LEFT:
x--;
if(x == 0+left) {
direction = UP;
bottom++;
}
break;
case UP:
y--;
if(y == 0+top) {
direction = RIGHT;
left++;
}
break;
}
}
for(y=0;y<n;y++) {
for(x=0;x<n;x++) {
printf("%c ",arr[y][x]);
}
puts("");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment