在日常的小游戏中,我们知道走迷宫的简要方法:
罗克说:“其实走迷宫可以不带线团,你按下面的三条规则去走,就能够走得进,也能够走得出”
第一条,进入迷宫后,可以任选一条道路往前走;
第二条,如果遇到走不通的死胡同,就马上返回,并在该路口做个记号;
第三条,如果遇到了叉路口,观察一下是否还有没有走过的通道。有,就任选一条通道往前走;没有,就顺着原路返回原来的叉路口,并做个记号。然后就重复第二条和第三条所说的走法,直到找到出口为止。如果要把迷宫所有地方都搜查到,还要加上一条,就是凡是没有做记号的通道都要走一遍。”
罗克说:“其实走迷宫可以不带线团,你按下面的三条规则去走,就能够走得进,也能够走得出”
第一条,进入迷宫后,可以任选一条道路往前走;
第二条,如果遇到走不通的死胡同,就马上返回,并在该路口做个记号;
第三条,如果遇到了叉路口,观察一下是否还有没有走过的通道。有,就任选一条通道往前走;没有,就顺着原路返回原来的叉路口,并做个记号。然后就重复第二条和第三条所说的走法,直到找到出口为止。如果要把迷宫所有地方都搜查到,还要加上一条,就是凡是没有做记号的通道都要走一遍。”
下面可以用代码实现简单的迷宫:
#include<iostream>
#include<stack>
#include<windows.h>//窗口
using namespace std;
struct seat
{
//构造函数
seat(int x, int y)
:_x(x)
,_y(y)
{}
int _x;
int _y;
};
#define ROW 10
#define COL 10
class Maze
{
public:
Maze(int map[ROW][COL])
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL;j++)
{
_map[i][j] = map[i][j];
}
}
}
//打印地图
void printmap()
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
cout << _map[i][j] << " ";
cout << endl;
}
}
//private:
// int _map[COL][ROW];
//};
//检测入口是否为通道
bool IsPass(const seat& s)
{
if (IsExit(s))
return true;
if (1 == _map[s._x][s._y])
return true;
return false;
}
//检测是否为出口
bool IsExit(const seat& s)
{
if (s._x<0||s._x>=ROW||s._y<0||s._y>=ROW)
return true;
return false;
}
//入口
bool passMaze(seat& enter)
{
if (!IsPass(enter))
{
cout << "入口非法" << endl;
return false;
}
stack<seat> s;//栈操作
s.push(enter);
while (!s.empty())
{
system("cls"); //刷新对话框
printmap();
Sleep(1000);//每隔1秒执行一次
//cout << endl;
//fflush(stdout);//刷新输出流
seat curpos = s.top();
if (IsExit(curpos))
{
return true;
}
_map[curpos._x][curpos._y] = 2;
//up
seat up(curpos);
up._x -= 1;
if (IsPass(up))
{
s.push(up);
continue;
}
//down
seat down(curpos);
down._x += 1;
if (IsPass(down))
{
s.push(down);
continue;
}
//left
seat left(curpos);
left._y -= 1;
if (IsPass(left))
{
s.push(left);
continue;
}
//right
seat right(curpos);
right._y += 1;
if (IsPass(right))
{
s.push(right);
continue;
}
//走错了
_map[curpos._x][curpos._y] = 5;
s.pop();
}
return false;
}
private:
int _map[COL][ROW];
};
int main()
{
int mapArr[ROW][COL] = {
{0,0,1,0,0,0,0,0,0,0},
{0,1,1,1,0,0,0,0,0,0},
{0,0,0,1,0,0,0,0,0,0},
{0,0,0,1,1,1,0,0,0,0},
{0,0,0,0,0,1,0,0,0,0},
{0,0,0,0,0,1,0,0,0,0},
{0,0,0,0,0,1,0,1,0,0},
{0,0,0,0,0,1,1,1,0,0},
{0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,1,0,0}
};
Maze map(mapArr);
map.printmap();
cout << endl;
if (map.passMaze(seat(9, 7)))
{
cout << "走出来了" << endl;
}
/*map.printmap();*/
system("pause");
return 0;
}
以上就是简单迷宫以C++的方式实现,部分注释已经在代码后面为大家给出,迷宫中主要用到了数据结构中栈的知识。动态升级版后面再做总结,有不足的地方欢迎大家提出!