POJ1101 二维图BFS
参考博文
https://blog.csdn.net/weixin_33786077/article/details/94190005
https://blog.csdn.net/weixin_40953222/article/details/80544928
题目分析
连连看,问你最少能拐几个弯
这道题全部参考博客的代码及思想,感觉很巧妙,代码也很精巧
核心:对于每个点,一般的广搜方法是对与其直接相连的每个点进行搜索,记录下上次的方向之后与这次的方向进行对比,更新转向次数;这里的广搜则是对其上下左右的一条射线上的每个点进行搜索,换句话说射线上的每个点都视为同一层,因为已经访问过的点不会再次访问,所以每一层都是一次拐弯
应该注意的细节是,终点在搜索开始前应该设置为空格;题目中的坐标系与矩阵的表示方式相冲突,在处理时把题目中的坐标系xy对调即可
代码
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int w,h,x1,y1,x2,y2,CNT = 0,cnt;
int dirx[]={1,-1,0,0},diry[]={0,0,1,-1},vis[99][99];
char a[99][99];
bool check(int x,int y){
return (x<=h+1&&x>=0&&y<=w+1&&y>=0 && a[x][y]!='X' && !vis[x][y]);
}
int bfs(int x, int y){
queue<int> aa,bb;
aa.push(x);bb.push(y);
while(!aa.empty()){
int tmpa = aa.front(),tmpb = bb.front();
aa.pop();bb.pop();
if(tmpa==x2&&tmpb==y2) return vis[tmpa][tmpb];
for(int i = 0;i <= 3;i++){
int tempa = tmpa,tempb = tmpb;
while(check(tempa+dirx[i],tempb+diry[i])){
tempa+=dirx[i];tempb+=diry[i];
vis[tempa][tempb] = vis[tmpa][tmpb]+1;
aa.push(tempa);bb.push(tempb);
}
}
}
return -1;
}
int main(){
while(scanf("%d%d",&w,&h)&&w){
memset(a,0,sizeof(a));
CNT++;
cnt = 0;
printf("Board #%d:\n",CNT);
for(int i = 1;i <= h;i++)
for(int j = 0;j <= w;j++)
scanf("%c",&a[i][j]);//注意会读入换行符
while(scanf("%d%d%d%d",&y1,&x1,&y2,&x2)&&x1){
cnt++;
memset(vis,0,sizeof(vis));
a[x2][y2] = ' ';
int ttt=bfs(x1,y1);
if(ttt!=-1) printf("Pair %d: %d segments.\n",cnt,ttt);
else printf("Pair %d: impossible.\n",cnt);
a[x2][y2] = 'X';
}
printf("\n");
}
}
567K 16MS