题意
东东有一张地图,想通过地图找到妹纸。地图显示,0表示可以走,1表示不可以走,左上角是入口,右下角是妹纸,这两个位置保证为0。既然已经知道了地图,那么东东找到妹纸就不难了,请你编一个程序,写出东东找到妹纸的最短路线。其中输入是一个5 × 5的二维数组,仅由0、1两数字组成,表示法阵地图。输出若干行,表示从左上角到右下角的最短路径依次经过的坐标,格式如样例所示。数据保证有唯一解。
思路
对于寻找路径我采用的是dfs方法,用两个常量数组表示表示上下左右四个移动方向,用一个vector和stack变量储存路径。
在dfs函数内,判断队尾元素是否是终点,不然就按照常量数组的索引顺序继续向下找,如果下一个点可以到达即tong()返回值为true,,则将该点标记,并且加入栈继续递归。当走到死路,即四个方向都没有办法到达时,则将该点从栈中释放掉,继续递归。
总结
这道题刚开始走了不少弯路,储存路径还自作聪明用一个数组存下每次操作的常量数组索引,蠢到忘记vector里已经存过了,对图的知识也忘得差不多了,得补一补了。
代码
#include<stdio.h>
#include<iostream>
using namespace std;
int sx=1,sy=1,ex=5,ey=5,step=0;
const int dx[4]={1,0,-1,0}; //表示移动方向
const int dy[4]={0,1,0,-1};
int mp[7][7]=
{
{1,1,1,1,1,1,1},
{1,0,0,0,0,0,1},
{1,0,0,0,0,0,1},
{1,0,0,0,0,0,1},
{1,0,0,0,0,0,1},
{1,0,0,0,0,0,1},
{1,1,1,1,1,1,1}
};
int arrive[7][7]=
{
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0}
};
struct point
{
int x,y;
point(int _x=1,int _y=1):x(_x),y(_y){};
};
vector<point> lu;
int pos[25];//存储路径
static int count=0;
bool tong(int i,int nx,int ny)
{
nx += dx[i];
ny += dy[i];
return (nx >= 1 && nx <= 5 && ny >= 1 && ny <= 5 && mp[nx][ny] != 1 && !arrive[nx][ny]);
}
void dfs()
{
point t=lu.back();
if(t.x==ex&&t.y==ey)return; //到达终点
int nx=t.x,ny=t.y;
if (tong(0,nx,ny)) {
nx += dx[0];
ny += dy[0];
arrive[nx][ny]=1;
pos[step++]=0;
point t(nx,ny);
lu.push_back(t);
dfs();
}
else if (tong(1,nx,ny)) {
nx += dx[1];
ny += dy[1];
arrive[nx][ny]=1;
pos[step++]=1;
point t(nx,ny);
lu.push_back(t);
dfs();
}
else if (tong(2,nx,ny)) {
nx += dx[2];
ny += dy[2];
arrive[nx][ny]=1;
pos[step++]=2;
point t(nx,ny);
lu.push_back(t);
dfs();
}
else if (tong(3,nx,ny)) {
nx += dx[3];
ny += dy[3];
arrive[nx][ny]=1;
pos[step++]=3;
point t(nx,ny);
lu.push_back(t);
dfs();
}
else
{
if(step) //返回上一层
step--;
lu.pop_back();
if(lu.size()){
point t=lu.back();
dfs();
}
else {
cout<<"no way"<<endl;
}
}
}
void showPath()
{
int xx=0,yy=0;
cout << "(" << xx << ", " << yy << ")" << endl;
for(int i=0;i<step;i++)
{
xx = xx + dx[pos[i]];
yy = yy + dy[pos[i]];
cout << "(" << xx << ", " << yy << ")" << endl;
}
}
int main()
{
point beg(1,1);
lu.push_back(beg);
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
cin>>mp[i][j];
dfs();
showPath();
return 0;
}