题目地址:点击打开链接
思路:感觉有点坑,(1)题目的图片没有正确显示,看我粘的图(2)输入的时候先输入的是纵坐标,后输入的是横坐标(3)每个输出块后要打印一个空行(4)本来都把打印step数组的输出给括掉了,结果输出错误,后来直接删掉就A了,和普通的BFS不太一样,和连连看差不多,要少拐弯,因为拐的越多,步数越多,要尽量沿着一个方向一直搜,为了方便理解打印了一下step数组
AC代码:
#include <iostream> #include <queue> #include <cstdio> #include <cstring> using namespace std; int step[80][80]; char map1[80][80]; int w,h,starti,startj,endi,endj; int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; struct point { int x,y; }in,out; bool check(int x,int y) { if(x >= 0 && x <= h+1 && y >=0 && y <= w+1 && map1[x][y] != 'X' && step[x][y] == 0) return true; return false; } void bfs() { int i; queue<point> q; in.x = starti; in.y = startj; map1[endi][endj] = ' '; q.push(in); while(!q.empty() && step[endi][endj] == 0) { out = q.front(); q.pop(); for(i=0; i<4; i++) { in.x = out.x + dir[i][0]; in.y = out.y + dir[i][1]; while(check(in.x,in.y) && step[endi][endj] == 0) { q.push(in); step[in.x][in.y] = step[out.x][out.y] + 1;//和它在一条线上的步数都是加1 in.x += dir[i][0]; in.y += dir[i][1]; } } } map1[endi][endj] = 'X'; } int main() { int i,l = 1,m; while(scanf("%d%d",&w,&h)) { if(w + h == 0) break; getchar();//读取回车,不然输入图的时候,第一行为空格 memset(map1,' ',sizeof(map1));//在外围框一层空格 for(i=1; i<=h; i++) { gets(&map1[i][1]);//用gets读入,getline会保留换行符,从1开始读入的,所以为map1[i][1] } printf("Board #%d:\n",l++); m = 1; while(scanf("%d%d%d%d",&startj,&starti,&endj,&endi)) { if(starti + startj + endi + endj == 0) break; memset(step,0,sizeof(step)); bfs(); if(step[endi][endj] == 0) printf("Pair %d: impossible.\n",m++); else printf("Pair %d: %d segments.\n",m++,step[endi][endj]); } printf("\n");//Output a blank line after each board. } return 0; }