标签:
Description
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
Input
Output
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
思路:独自ac了这道题,感觉挺好。。这和最少步数类似,不同的是要记录出路径。可以用flag数组标记。如果是此点是被向上移动得到的,flag[now.x][now.y]=1;被右移得到的,赋为2,下移得到的,赋为3,被左移得到的,此点flag[now.x][now.y]记为4。满足从没有被访问过,且是可以走的路(0),在5行5列范围内就入队列。为什么要是没有被访问过的呢?因为比如开始这个点没有访问过,被flag标记过了,已经知道此点的前一步是谁了,但是下一个路径又到了此点,如果不限制此点是否访问,那么满足限制条件,flag又重新被赋值,不是最短路了,那个之前最短的路径的标记就被覆盖掉了,我是这样认为的。。然后到了重点,然后再根据flag标记,回去,把横纵坐标放到a,b数组中,直到回到(0,0)位置,按要求输出即可。。
#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
int num[5][5],visited[5][5],flag[5][5];
int a[11],b[11],k,g;
int x[4]={0,1,0,-1};
int y[4]={1,0,-1,0};
struct point
{
int x;
int y;
};
void bfs()
{
queue<point>q;
point now,next;
now.x=0;
now.y=0;
q.push(now);
while(!q.empty())
{
int i;
next=q.front();
q.pop();
if(next.x==4 &&next.y==4)
{
k=0;g=0;
a[k++]=next.x;
b[g++]=next.y;
while(next.x>=0 &&next.y>=0)
{
if(next.x==0 &&next.y==0)
return ;
if(flag[next.x][next.y]==1)
{
next.x++;
a[k++]=next.x;
b[g++]=next.y;
}
else if(flag[next.x][next.y]==2)
{
next.y--;
a[k++]=next.x;
b[g++]=next.y;
}
else if(flag[next.x][next.y]==3)
{
next.x--;
a[k++]=next.x;
b[g++]=next.y;
}
else if(flag[next.x][next.y]==4)
{
next.y++;
a[k++]=next.x;
b[g++]=next.y;
}
}
}
for(i=0;i<4;i++)
{
now.x=next.x+x[i];
now.y=next.y+y[i];
if(now.x>=0 && now.x<5 &&now.y>=0 &&now.y<5 &&num[now.x][now.y]==0 && !visited[now.x][now.y])
{
visited[now.x][now.y]=1;
if(i==0)
flag[now.x][now.y]=2;//走右移
else if(i==1)
flag[now.x][now.y]=3;//bei走下移
else if(i==2)
flag[now.x][now.y]=4;//走左移
else
flag[now.x][now.y]=1;//走上移
q.push(now);
}
}
}
}
int main()
{
int i,j;
memset(visited,0,sizeof(visited));
memset(flag,0,sizeof(flag));
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
cin>>num[i][j];
}
bfs();
for(i=k-1;i>=0;i--)
{
printf("(%d, %d)\n",a[i],b[i]);
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/zuguodexiaoguoabc/article/details/45100665