我的思路是网格的四周全部置为'*',设置sign数组记录起始格

#include <stdio.h> #include <cstring> char a[20][20]; int sign[20][20]; int n = 1; int main() { int r, c, cnt, yes, first = 1; while(scanf("%d",&r)==1) { memset(sign,0,sizeof(sign)); cnt = 1; yes = 0; if(r == 0) break; scanf("%d",&c); getchar(); for(int i = 1; i <= r; i ++) { for(int j = 1; j <= c; j ++) {scanf("%c",&a[i][j]);} getchar(); } for(int i = 0; i <= r+1; i ++) a[i][0] = a[i][c+1] = '*'; for(int j = 0; j <= c+1; j++) a[0][j] = a[r+1][j] = '*'; for(int i = 1; i <= r; i++) for(int j = 1; j <= c; j++) if((a[i-1][j] == '*' || a[i][j-1] == '*')&&a[i][j] !='*') sign[i][j] = cnt ++; if(!first) printf("\n"); first = 0; printf("puzzle #%d:\nAcross\n",n); for(int i = 1; i <= r; i ++) for(int j = 1; j <= c; j ++) { if(sign[i][j]) printf("%3d.",sign[i][j]); while(a[i][j] != '*') { printf("%c",a[i][j]); j ++; yes = 1; } if(yes) { printf("\n"); yes = 0; } } printf("Down\n"); for(int i = 1; i <= r; i ++) for(int j = 1; j <= c; j ++) { int m = i; if(sign[i][j]) printf("%3d.",sign[i][j]); while(a[i][j] != '*') { printf("%c",a[i][j]); a[i][j] = '*'; sign[i][j] = 0; yes = 1; i ++; } if(yes) { printf("\n"); yes = 0; } i = m; } n++; } return 0; }