你这里9个格,必然总有空间填够9个字母,当然是第10个在外面了,还用算的么?
授人以渔,不授人以鱼。
#include <stdio.h> #include <time.h> #include <stdlib.h> #define MAXX 12 #define MAXY 12 int main() { int i, j, count = 1; char map[MAXX][MAXY]; const char str='A'; srand( (unsigned) time(NULL) ); for (i=0; i<MAXX; i++) { for (j=0; j<MAXY; j++) { if(i == 0 || j == 0 || i == MAXX-1 || j == MAXY-1) map[i][j] = ' '; else map[i][j] = '.'; } } i = 1; j = 1; map[1][1] = str; while(1) { if(map[i-1][j ] != '.' && map[i+1][j ] != '.' && map[i ][j-1] != '.' && map[i ][j+1] != '.') break; switch (rand()%4) //0、1、2、3分别代表上、下、左、右 { case 0: if(map[i-1][j] == '.') { map[--i][j]=str+count; count ++; } break; case 1: if(map[i+1][j] == '.') { map[++i][j]=str+count; count ++; } break; case 2: if(map[i][j-1] == '.') { map[i][--j]=str+count; count ++; } break; case 3: if(map[i][j+1] == '.') { map[i][++j]=str+count; count ++; } break; } if(count == 26) break; } for(i=0;i<MAXX;++i) { for(j=0;j<MAXY;++j) printf("%c ",map[i][j]); printf("\n"); } getchar(); return 0; }