迷宫是许多小方格构成的矩形,在每个小方格中有的是墙(用1表示),有的是路(用0表示)。走迷宫就是从一个小方格沿上、下、左、右四个方向到邻近的方格,当然不能穿墙。设迷宫的入口是在左上角(1,1),出口是在右下角(8,8)。根据给定的迷宫,找出一条从入口到出口的路径。
解法一(深度优先遍历,打印所有可行的路径):
#include
using namespace std;
int maze[8][8] = {{0,0,0,0,0,0,0,0},{0,1,1,1,1,0,1,0},{0,0,0,0,1,0,1,0},{0,1,0,0,0,0,1,0},
{0,1,0,1,1,0,1,0},{0,1,0,0,0,0,1,1},{0,1,0,0,1,0,0,0},{0,1,1,1,1,1,1,0}};
//下、右、上、左
const int fx[4] = {1,0,-1,0};
const int fy[4] = {0,1,0,-1};
//maze[i][j] = 3;//标识已走
//maze[i][j] = 2;//标识死胡同
//maze[i][j] = 1;//标识墙
//maze[i][j] = 0;//标识可以走
//打印路径
void printPath()
{
for (int i=0;i<8;++i)
{
for (int j=0;j<8;++j)
{
if (3 == maze[i][j])
{
cout<<"V";
}
else
{
cout<<"*";
}
}
cout<
}
cout<
}
void search(int i, int j)
{
int newx;
int newy;
for (int k=0;k<4;++k)
{
newx = i+fx[k];
newy = j+fy[k];
//如果不是墙,且没有走过
if (newx>=0 && newx <8 && newy>=0 && newy<8 && 0 == maze[newx][newy])
{
maze[newx][newy] = 3;
if (7 == newx && 7 == newy)
{
printPath();
maze[newx][newy] = 0;
}
else
{
search(newx,newy);
}
}
}
**//回溯的时候将此点标记未访问,这样下一条路径也可以访问**
maze[i][j] = 0;
}
int main()
{
maze[0][0] = 3;
search(0,0);
return 0;
}
解法二(广度优先遍历):
#include
#include
using namespace std;
int maze[8][8] = {{0,0,0,0,0,0,0,0},{0,1,1,1,1,0,1,0},{0,0,0,0,1,0,1,0},{0,1,0,0,0,0,1,0},
{0,1,0,1,1,0,1,0},{0,1,0,0,0,0,1,1},{0,1,0,0,1,0,0,0},{0,1,1,1,1,1,1,0}};
//下、右、上、左
const int fx[4] = {1,0,-1,0};
const int fy[4] = {0,1,0,-1};
struct sq{
int x;
int y;
int pre;
};
//标记路径,正确的点值赋为3
void markPath(const vector &q, int index)
{
sq tmp = q[index];
maze[tmp.x][tmp.y] = 3;
if ( 0 == tmp.x && 0 == tmp.y )
{
return ;
}
else
{
markPath(q, tmp.pre);
}
}
//打印路径
void printPath()
{
for (int i=0;i<8;++i)
{
for (int j=0;j<8;++j)
{
if (3 == maze[i][j])
{
cout<<"v";
}
else
{
cout<<"*";
}
}
cout<cout<//检查点(i,j)是否满足
bool check(int i, int j)
{
if (i >= 0 && i<8 && j>=0 && j<8 && 0 == maze[i][j])
{
return true;
}
return false;
}
void search()
{
//模仿队列,之所以不用真正的队列,因为后面需要通过下标对队列进行随机访问
vector q;
int qh = 0;
sq fnode;
fnode.pre = -1;
fnode.x = 0;
fnode.y = 0;
//标记已访问
maze[fnode.x][fnode.y] = -1;
q.push_back(fnode);
int qe = 1;
sq tmp;
while (qh != qe)
{
//出队
tmp = q[qh];
++qh;
int newx, newy;
for (int k=0;k<4;++k)
{
newx = tmp.x + fx[k];
newy = tmp.y + fy[k];
if (check(newx, newy))
{
sq n_node;
n_node.pre = qh - 1;
n_node.x = newx;
n_node.y = newy;
//入队
q.push_back(n_node);
++qe;
//找到出口,打印
if (7 == newx && 7 == newy)
{
markPath(q, qe-1);
printPath();
return;
}
}
}
//maze[tmp.x][tmp.y] = -1;
}
}
int main()
{
maze[0][0] = 3;
search();
return 0;
}