题目连接: ~( ̄▽ ̄~)(~ ̄▽ ̄)~
相邻的两个的segments为1,注意格式问题,wa了半天就在这2点上,郁闷
code:
#include <stdio.h> #include <string.h> int X1 = 0, Y1 = 0, X2 = 0, Y2 = 0, w = 0, h = 0, count2 = 0; char map[80][80]; int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}, used[80][80]; typedef struct { int x, y, count; }node; node step, quene[80*80]; void bfs() { int i = 0, front = 0, rear = 0, x = 0, y = 0, fx = 0, fy = 0, count = 0; quene[rear++] = step; while(front<rear) { step = quene[front++] ; x = step.x; y = step.y; count = step.count; for(i = 0; i<4; i++) { fx = x+dir[i][0]; fy = y+dir[i][1]; while(map[fx][fy] != 'X' && fx>=0 && fx<=h+1 && fy>=0 && fy<=w+1)//一行一列全入队 { if(!used[fx][fy]) { used[fx][fy] = 1; step.x = fx; step.y = fy; step.count = count+1; quene[rear++] = step; } fx += dir[i][0]; fy += dir[i][1]; } if(fx == X2 && fy == Y2 ) { printf("Pair %d: %d segments.\n",++count2, count+1); return; } } } printf("Pair %d: impossible.\n", ++count2); } int main() { int i = 0, j = 0,count1 = 0; while(scanf("%d %d",&w, &h) , w || h) { getchar(); for(i = 0; i<w+2; i++)//在图的最外边在加一层框,这层框可做为路径走 map[0][i] = ' '; for(i = 1; i<=h; i++) { map[i][0] = ' '; for(j = 1; j<=w; j++) { scanf("%c",&map[i][j]); } getchar(); map[i][j] = ' '; } for(i = 0; i<w+2; i++) map[h+1][i] = ' '; printf("Board #%d:\n", ++count1); count2 = 0; while(scanf("%d %d %d %d",&Y1, &X1, &Y2, &X2) && (X1 || Y1 || X2 || Y2)) { memset(used,0,sizeof(used)); step.x = X1; step.y = Y1; step.count = 0; if(X1 == X2 && Y1 == Y2) printf("Pair %d: 0 segments.\n", ++count2); else bfs(); } printf("\n"); } return 0; }