Ruby勉強 -- 追記:C言語の場合
C言語だとダメというわけでもないような。
A*が書きづらいというだけかな。しかし配列確保してポインタ付け替えてくだけでいいからむしろC言語の方が簡単なんじゃないかな。
言語の違いは決定的なものではないように思う。Javaでは書きたくないけど。
/* http://okajima.air-nifty.com/b/2010/01/post-abc6.html */ #include <stdio.h> #define MAX_SIZE 100 #define _(X,Y,S) (((Y)*S)+X) void solve_map(int x, int y, int d, char map[], int cmap[], int xs) { if (cmap[_(x,y,xs)]>d && map[_(x,y,xs)]==' ') cmap[_(x,y,xs)]=d; if (cmap[_(x-1,y,xs)]>d+1 && map[_(x-1,y,xs)]==' ') solve_map(x-1,y,d+1,map,cmap,xs); if (cmap[_(x+1,y,xs)]>d+1 && map[_(x+1,y,xs)]==' ') solve_map(x+1,y,d+1,map,cmap,xs); if (cmap[_(x,y-1,xs)]>d+1 && map[_(x,y-1,xs)]==' ') solve_map(x,y-1,d+1,map,cmap,xs); if (cmap[_(x,y+1,xs)]>d+1 && map[_(x,y+1,xs)]==' ') solve_map(x,y+1,d+1,map,cmap,xs); } int select_route(int x, int y, char map[], int cmap[], int xs) { int min_d; if (map[_(x,y,xs)]==' ') map[_(x,y,xs)]='$'; if (map[_(x-1,y,xs)]=='S') return 1; if (map[_(x+1,y,xs)]=='S') return 1; if (map[_(x,y-1,xs)]=='S') return 1; if (map[_(x,y+1,xs)]=='S') return 1; min_d=cmap[_(x,y,xs)]; if (cmap[_(x-1,y,xs)]<min_d && map[_(x-1,y,xs)]==' ') min_d=cmap[_(x-1,y,xs)]; if (cmap[_(x+1,y,xs)]<min_d && map[_(x+1,y,xs)]==' ') min_d=cmap[_(x+1,y,xs)]; if (cmap[_(x,y-1,xs)]<min_d && map[_(x,y-1,xs)]==' ') min_d=cmap[_(x,y-1,xs)]; if (cmap[_(x,y+1,xs)]<min_d && map[_(x,y+1,xs)]==' ') min_d=cmap[_(x,y+1,xs)]; if (cmap[_(x-1,y,xs)]==min_d && map[_(x-1,y,xs)]==' ') return select_route(x-1,y,map,cmap,xs); if (cmap[_(x+1,y,xs)]==min_d && map[_(x+1,y,xs)]==' ') return select_route(x+1,y,map,cmap,xs); if (cmap[_(x,y-1,xs)]==min_d && map[_(x,y-1,xs)]==' ') return select_route(x,y-1,map,cmap,xs); if (cmap[_(x,y+1,xs)]==min_d && map[_(x,y+1,xs)]==' ') return select_route(x,y+1,map,cmap,xs); return 0; } int main(int argc, char *argv[]) { char map[MAX_SIZE*MAX_SIZE]; int cmap[MAX_SIZE*MAX_SIZE]; int xsize, ysize; int sx, sy; /* start */ int gx, gy; /* goal */ FILE *f; char c; int i, x, y, pos; /* load data */ if ((f=fopen(argv[1],"r"))= NULL) exit(1); xsize = 0; for (i=0,pos=0; (c=fgetc(f))!=EOF; i++) { if (c!='\n') { map[pos++]=c; switch (c) { case 'S': sx=(pos-1)%xsize; sy=(pos-1)/xsize; break; case 'G': gx=(pos-1)%xsize; gy=(pos-1)/xsize; break; } } else if (xsize==0) { xsize=i; } } ysize = i/xsize; fclose(f); for (i=0; i<xsize*ysize; i++) cmap[i] = 8192; /* solve */ solve_map(sx, sy, 0, map, cmap, xsize); if (select_route(gx, gy, map, cmap, xsize) == 1) { /* print data */ for (y=0; y<ysize; y++) { for (x=0; x<xsize; x++) putchar(map[_(x,y,xsize)]); putchar('\n'); } } else { printf("fail!\n"); exit(1); } return 0; }