http://codeup.cn/problem.php?cid=100000609&pid=1
B-DFS or BFS?(走迷宫)
难度:B(中等题)
类型:BFS+状态变化
剪枝思路:当now.step==8时,石头必定全部消失,则必能到达终点
PS:这道题只用定性判断是否能够走到终点,如果定量输出最少步数的话难度upup
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
int sx,sy,ex,ey;
char ma[8][8];//地图
int dir[9][2]={{0,1},{0,-1},{1,0},{-1,0},{1,1},
{-1,-1},{1,-1},{-1,1},{0,0}};//方向向量
struct node//BFS 队列中的状态数据结构
{
int x,y;//坐标位置
int step;
}s;
node now,nex;//定义2个状态,当前和下一个
int judge(int x,int y)//条件判断
{
if(ma[x][y]=='S')
return 0;
if(x>7||x<0||y<0||y>7)
return 0;
return 1;
}
void change()//落石
{
for(int i=7;i>=0;i--)
for(int j=7;j>=0;j--)
if(ma[i][j]=='S')
{
ma[i][j]='.';
if(i<=6)
ma[i+1][j]='S';
}
}
void bfs(int c)
{
int flag=0;//终点标志
queue<node>q;//BFS队列
s.x=sx,s.y=sy,s.step=0;
q.push(s);//入队
int level=0;
while(!q.empty())
{
now=q.front();//取队首元素进行扩展
if(now.step!=level)
{
change();
level=now.step;
}
if(ma[now.x][now.y]=='S')//撞墙出队
{
q.pop();
continue;//直接下个队员
}
if(now.step==8)//石头清空,必到终点
{
flag=1;
break;
}
q.pop();//队首元素出队
for(int i=0;i<9;i++)//走路
{
if(judge(now.x+dir[i][0],now.y+dir[i][1])==1)
{
nex.x=now.x+dir[i][0];
nex.y=now.y+dir[i][1];
nex.step=now.step+1;
q.push(nex);
}
}
}
if(flag==0)
printf("Case #%d: No\n",c);
else
printf("Case #%d: Yes\n",c);
}
int main()
{
int t,cnt=1;
scanf("%d",&t);
while(t--)
{
for(int i=0;i<8;i++)
scanf("%s",ma[i]);
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
if(ma[i][j]=='U')
sx=i,sy=j;
if(ma[i][j]=='A')
ex=i,ey=j;
}
}
bfs(cnt++);
}
return 0;
}