您的位置:首页 > 产品设计 > UI/UE

uestc 一个简单的迷宫问题

2015-01-31 23:39 232 查看
我不知道化成网格线什么意思啊。。。 :(

如果我写一步一搜的话肯定很麻烦。。

大牛代码 理解以上两点之后再重新做。。sigh~

#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
int n,m;
int map[55][55];
bool vis[4][55][55];
struct node
{
int x,y;
int dr;   //方向
int step;
bool operator<(const node &t)const
{
return t.step<step;
}
}S,E;
bool judge(int x,int y)
{
if(x>=0 && x<n-1 && y>=0 && y<m-1)
{
return true;
}
return false;
}
int bfs()
{
priority_queue<node>q;
q.push(S);
node now,next,temp;
memset(vis, false, sizeof(vis));
vis[S.dr][S.x][S.y]=true;
while (!q.empty())
{
next=now=temp=q.top();
q.pop();
if(now.x==E.x && now.y==E.y)
{
return now.step;
}
for (int i=-1; i<4; i++)
{
if(i<=0)
{
now.step=temp.step+1;
if(i==-1)
{
now.dr=(1+temp.dr)%4;  //右转
}
if(i==0)
{
now.dr=(3+temp.dr)%4;  //左转
}
if(!vis[now.dr][now.x][now.y])
{
vis[now.dr][now.x][now.y]=true;
q.push(now);
}
}
else
{
next.step=temp.step+1;
if(next.dr==0)  //向上走
{
next.x=temp.x-i;
}
if(next.dr==1)  //向右走
{
next.y=temp.y+i;
}
if(next.dr==2) //向下走
{
next.x=temp.x+i;
}
if(next.dr==3) //向左走
{
next.y=temp.y-i;
}
//走i步过程中有一步走不通就不得行了
if(!judge(next.x, next.y) || map[next.x][next.y]==1)
{
break;
}
if(!vis[next.dr][next.x][next.y])
{
q.push(next);
vis[next.dr][next.x][next.y]=true;
}
}
}
}
return -1;
}
int main()
{
while (scanf("%d%d",&n,&m) && (n||m))
{
for (int i=0; i<n; i++)
{
for (int j=0; j<m; j++)
{
scanf("%d",&map[i][j]);

//把n*m的矩阵化成(n-1)*(m-1)的网格线矩阵。
if(map[i][j]==1)
{
map[i][j]=1;
if(i>=1)
{
map[i-1][j]=1;
if(j>=1)
{
map[i-1][j-1]=1;
}
}
if(j>=1)
{
map[i][j-1]=1;
if(i>=1)
{
map[i-1][j-1]=1;
}
}
}
}
}
scanf("%d%d%d%d%d",&S.x,&S.y,&E.x,&E.y,&S.dr);
S.x--,S.y--,E.x--,E.y--;
S.step=0;
printf("%d\n",bfs());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: