您的位置:首页 > 其它

走迷宫

2015-07-21 18:18 363 查看
#include<iostream>
#include<stdio.h>
#include<string>
#include<cstring>
using namespace std;
const int Max = 101;
bool  vis[Max][Max];
int fa[Max][Max],q[Max*Max],dist[Max][Max],last_dir[Max][Max],mat[Max][Max];
int n,m,dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};
char name[] = {'U','D','L','R'};
void bfs(int x,int y)
{
int front = 0,rear = 0,d,u;
u = x*m + y;
vis[x][y] = 1;fa[x][y] = u;dist[x][y] = 0;
q[rear++] = u;
while(front < rear)
{
u = q[front++];
x=u/m;
y=u%m;
cout<<"x= "<<x<<" "<<"y= "<<y<<endl;
for(d = 0; d < 4; d ++)
{

int nx = x+dx[d],ny = y + dy[d];
cout<<"nx= "<<nx<<"ny= "<<ny<<endl;
if(nx >= 0 && nx <n && ny >= 0 && ny < m && !mat[nx][ny] && !vis[nx][ny])
{
cout<<"YYY"<<endl;
int v = nx*m+ny;
q[rear++]= v;  //没办法把图中的节点装进队列,就用v节点记录,放进队列,需要时还原。
vis[nx][ny] = 1;
fa[nx][ny] = u;
dist[nx][ny] = dist[x][y] + 1;
cout<<dist[nx][ny]<<endl;
last_dir[nx][ny] = d;
}
}
}
}
void print_path(int x,int y)
{
int fx = fa[x][y]/m;
int fy = fa[x][y]%m;
if(fx != x ||fy != y)
{
print_path(fx,fy);
putchar(name[last_dir[x][y]]);
}
}
int main()
{  //第一个错误就是n和m重定义。造成bfs里面有了除零错误。。。。。

while(cin>>n>>m)  //输入行数和列数
{
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;  //输入其实位置和终止位置
for(int i = 0;i != n; i ++)
{
for(int j = 0;j != m ; j ++)
{
cin>>mat[i][j];  //由于是int型输入,所以一定要保证两个数字之间有空格
}
}
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
bfs(x1,y1);
cout<<dist[x2][y2]<<endl;
print_path(x2,y2);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: