1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 int m[22][22]; 6 int di[4][2] = 7 { 8 { -1, 0 }, 9 { 0, 1}, 10 { 1, 0 }, 11 { 0, -1 } 12 }; 13 14 int 15 main(int argc, char **argv) 16 { 17 char ibuf[512], *s, obuf[400/5+2]; 18 int i, n, ir, ic, r, c, ch, cnt, dir, loop, io, or, oc; 19 20 if (fgets(&(ibuf[0]), sizeof(ibuf), stdin) == NULL) 21 { 22 return(0); 23 } 24 n = atoi(&(ibuf[0])); 25 #ifdef MKINPUT 26 printf("%d\n", n); 27 #endif 28 for (i = 1; i <= n; i++) 29 { 30 if (fgets(&(ibuf[0]), sizeof(ibuf), stdin) == NULL) 31 { 32 printf("premature eof\n"); 33 break; 34 } 35 r = atoi(&(ibuf[0])); 36 or = r; 37 s = strchr(&(ibuf[0]), ' '); 38 if (s == NULL) 39 { 40 printf("no separator space 1(%d)\n", i); 41 break; 42 } 43 s++; 44 c = atoi(s); 45 oc = c; 46 s = strchr(s, ' '); 47 if (s == NULL) 48 { 49 printf("no separator space 2(%d)\n", i); 50 break; 51 } 52 s++; 53 /* Fill in matrix */ 54 for (ir = 1; ir <= r; ir++) 55 { 56 m[ir][0] = -1; 57 for (ic = 1; ic <= c; ic++, s++) 58 { 59 m[ir][ic] = *s - '0'; 60 } 61 /* Set up border */ 62 m[ir][ic] = -1; 63 } 64 /* Set up border */ 65 for (c = 0; c <= ic; c++) 66 { 67 m[ir][c] = -1; 68 m[0][c] = -1; 69 } 70 r = 1; 71 c = 1; 72 ch = 0; 73 dir = 1; 74 for (io = 0, cnt = 0;;) 75 { 76 ch = (ch<<1) | m[r][c]; 77 m[r][c] = -1; 78 cnt++; 79 if (cnt == 5) 80 { 81 if (ch == 0) 82 { 83 obuf[io++] = ' '; 84 } 85 else 86 { 87 obuf[io++] = 'A' + ch - 1; 88 } 89 cnt = 0; 90 ch = 0; 91 } 92 loop = 0; 93 /* Next move taken? */ 94 while (m[r+di[dir][0]][c+di[dir][1]] == -1) 95 { 96 dir++; 97 if (dir >= 4) 98 { 99 dir = 0; 100 if (loop++) 101 { 102 break; 103 } 104 } 105 } 106 if (loop > 1) 107 { 108 break; 109 } 110 r += di[dir][0]; 111 c += di[dir][1]; 112 } 113 /* Trim trailing */ 114 while (--io >= 0 && obuf[io] == ' ') 115 { 116 ; 117 } 118 obuf[++io] = '\0'; 119 #ifndef MKINPUT 120 printf("%d %s\n", i, &(obuf[0])); 121 #else 122 printf("%d %d %s\n", or, oc, &(obuf[0])); 123 #endif 124 125 } 126 return(0); 127 } 128 129