Meaning of the questions:
There is a map, the map in the upper left corner is the entrance, the lower right corner for export. Map, 1 can not walk, 0 can go. To ensure that import, export zero. Write a program to find the entrance to the exit of the shortest route.
Input:
Input is a 5 × 5 two-dimensional array, just the two numbers 0,1, representation positions in FIG.
The Input the Sample:
0. 1 0 0 0
0 0. 1. 1 0
0 0. 1. 1 0
0 0 0. 1 0
0 0. 1. 1 0
Output:
A plurality of output lines, represents the shortest path from upper left to lower right corner coordinates sequentially passes. Ensure data has a unique solution.
The Sample the Output:
(0, 0)
(. 1, 0)
(2, 0)
(. 3, 0)
(. 3,. 1)
(. 3, 2)
(2, 2)
(. 1, 2)
(0, 2)
(0 , 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)
Ideas:
The map is initialized to an array of 5 * 5, with a map showing the obstacles, with 0 map to reach the place but has not yet arrived. From the start breadth-first search (the BFS), has been used since the number 0, so the use of digital> 2 marking the path length (ie start tag 2, the starting point can be reached around a point labeled 3, this and so on), the search stops encountered exit. Finally, according to exit from the record marked paths (each looking to record a small path length than the current point of a point) until you return to the starting point, find the shortest path.
Code:
#include <iostream>
#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;
const int maxn=5;
int vis[maxn][maxn];
int dx[]={1,-1,0,0},
dy[]={0,0,1,-1};
int sx=0,sy=0,tx=4,ty=4;
struct Point{
int x;
int y;
Point(int thex,int they)
{
x=thex,y=they;
}
};
queue<Point> q;
void bfs()
{
q.push(Point(sx,sy));
vis[sx][sy]=2;
while(!q.empty())
{
Point now=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int x=now.x+dx[i];
int y=now.y+dy[i];
if(x>=0&&x<maxn&&y>=0&&y<maxn&&vis[x][y]==0)
{
vis[x][y]=vis[now.x][now.y]+1;
q.push(Point(x,y));
if(x==tx&&y==ty)
return;
}
}
}
}
void print()
{
vector<Point> v;
Point now(tx,ty);
v.push_back(Point(tx,ty));
while(true)
{
if(now.x==sx&&now.y==sy)
{
//printf("(%d,%d)\n",sx,sy);
break;
}
for(int i=0;i<4;i++)
{
int x=now.x+dx[i],y=now.y+dy[i];
if(x>=0&&x<maxn&&y>=0&&y<maxn&&vis[x][y]==vis[now.x][now.y]-1)
{
v.push_back(Point(x,y));
now.x=x,now.y=y;
break;
}
}
}
vector<Point>::reverse_iterator it=v.rbegin();
printf("(%d, %d)",it->x,it->y);
it++;
for(;it!=v.rend();it++)
printf("\n(%d, %d)",it->x,it->y);
}
int main(int argc, char** argv) {
for(int i=0;i<maxn;i++)
for(int j=0;j<maxn;j++)
cin>>vis[i][j];
bfs();
print();
return 0;
}