#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<algorithm>
using namespace std;
int H,L,ha,la,hb,lb,MIN;
int b[80][80];
int x[4][2]= {{-1,0},{0,1},{1,0},{0,-1}};
void dfs(int h,int l,int dir,int step) {
if(h==hb&&l==lb) {//终止条件
if(step<MIN) MIN=step;
return;
}
if(step>=MIN) return;//剪枝
for(int i=0; i<4; i++) {
int hh=h+x[i][0],ll=l+x[i][1];
if(hh>=0&&hh<=H+1&&ll>=0&&ll<=L+1&&b[hh][ll]==0) {//进入条件
b[hh][ll]=1;
if(dir!=i) dfs(hh,ll,i,step+1);
else dfs(hh,ll,i,step);
b[hh][ll]=0;//回溯
}
}
}
int main() {
int k1=1;
while(scanf("%d%d",&L,&H),L) {
printf("Board #%d:\n",k1);
k1++;
memset(b,0,sizeof(b));
getchar();
char c;
for(int i=1; i<=H; i++) {
for(int j=1; j<=L; j++) {
scanf("%c",&c);
if(c=='X') b[i][j]=1;
else b[i][j]=0;
}
getchar();
}
int k2=1;
while(scanf("%d%d%d%d",&la,&ha,&lb,&hb),ha) {
MIN=1e6;
b[hb][lb]=0;//保证可以进入终点
dfs(ha,la,-1,0);
b[hb][lb]=1;
if(MIN<1e6) printf("Pair %d: %d segments.\n",k2,MIN);
else printf("Pair %d: impossible.\n",k2);
k2++;
}
printf("\n");
}
return 0;
}
POJ小游戏
最新推荐文章于 2023-11-12 17:41:41 发布
本文深入探讨了一种迷宫寻路算法,通过深度优先搜索(DFS)策略,结合回溯技术,在给定的迷宫地图中寻找从起点到终点的最短路径。算法首先定义了迷宫的边界和障碍物,然后利用递归方式遍历所有可能的路径,通过剪枝技术优化搜索过程,避免无效路径的重复探索,最终找到最短路径。
1214

被折叠的 条评论
为什么被折叠?



