迷宫问题属于简单的搜索问题,用dfs或者bfs即可比较轻松的解决。这里附上两种写法,用栈实现的dfs和用队列实现的bfs。
队列实现bfs代码:
#include<iostream>
#include<stack>
#include<queue>
#include<algorithm>
#include<cstdio>
using namespace std;
#define INF 0x3f3f3f
typedef pair<int, int> pir;
int maze[10][10], dis[10][10];
int dir[4][2] = { 0,1,1,0,0,-1,-1,0 };
queue<pir>q;
void init()
{
int i, j;
memset(dis, INF, sizeof(dis));
for (i = 0; i < 8; ++i) {
for (j = 0; j < 8; ++j) {
cin >> maze[i][j];
dis[i][j] = INF;
}
}
}
bool check(int x, int y)
{
return 0 <= x && x < 8 && 0 <= y && y < 8;
}
void bfs()
{
int xx, yy, x, y, t;
q.push({ 7,7 }); dis[7][7] = 0;
while (!q.empty()) {
pir tmp = q.front();
q.pop();
x = tmp.first;
y = tmp.second;
for (int i = 0; i < 4; ++i) {
xx = x + dir[i][0];
yy = y + dir[i][1];
if (check(xx, yy) && maze[xx][yy] == 0)
{
t = dis[x][y] + 1;
dis[xx][yy] = min(t, dis[xx][yy]);
maze[xx][yy] = 2;
q.push({ xx,yy });
}
}
}
}
void print()
{
int xx, yy, x, y;
x = 0, y = 0;
printf("(1 ,1)\n");
while (x < 7 || y < 7) {
for (int i = 0; i < 4; ++i) {
xx = x + dir[i][0];
yy = y + dir[i][1];
if (dis[xx][yy] == dis[x][y] - 1) {
printf("(%d ,%d)\n", xx + 1, yy + 1);
x = xx; y = yy; break;
}
}
}
}
int main()
{
init();
bfs();
print();
return 0;
}
测试样例:
0 0 1 0 0 0 1 0
0 1 1 1 0 0 0 0
0 1 0 0 0 1 0 0
0 0 0 0 0 0 0 0
0 0 1 0 0 0 1 0
0 0 0 0 1 1 0 0
0 0 0 1 0 0 0 0
0 1 1 1 0 1 1 0
输出:
(1 ,1)
(2 ,1)
(3 ,1)
(4 ,1)
(4 ,2)
(4 ,3)
(4 ,4)
(4 ,5)
(4 ,6)
(4 ,7)
(4 ,8)
(5 ,8)
(6 ,8)
(7 ,8)
(8 ,8)
用栈实现的dfs代码:
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
int maze[10][10] =
{
1,1,1,1,1,1,1,1,1,1,
1,0,0,1,0,0,0,1,0,1,
1,0,1,1,1,0,0,0,0,1,
1,0,1,0,0,0,1,0,0,1,
1,0,0,0,0,0,0,0,0,1,
1,0,0,1,0,0,0,1,0,1,
1,0,0,0,0,1,1,0,0,1,
1,0,0,0,1,0,0,0,0,1,
1,0,1,1,1,0,1,1,0,1,
1,1,1,1,1,1,1,1,1,1,
};
int dir[4][2] = { 0,1,1,0,0,-1,-1,0 };
stack<int>st;
inline bool check(int x, int y)
{
return 0 <= x && x <= 8 && 0 <= y && y <= 8;
}
void search(int x, int y)
{
int i, tmp; maze[8][8] = 2;
while (x != 1 || y != 1) {
for (i = 0; i < 4; ++i) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (check(xx, yy) && !maze[xx][yy]) {
maze[xx][yy] = 2;
st.push(i);
x = xx; y = yy;
break;
}
}
while (i >= 4) {
maze[x][y] = 0; tmp = st.top();
x = x - dir[tmp][0];
y = y - dir[tmp][1];
st.pop();
for (i = tmp + 1; i < 4; ++i) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (check(xx, yy) && !maze[xx][yy]) {
maze[xx][yy] = 2;
st.push(i);
x = xx; y = yy;
break;
}
}
}
}
}
int main()
{
search(8, 8);
int x = 1, y = 1;
while (!st.empty())
{
printf("(%d ,%d)\n", x, y);
x = x - dir[st.top()][0];
y = y - dir[st.top()][1];
st.pop();
}
printf("(%d ,%d)\n", x, y);
return 0;
}
输出结果:
(1 ,1)
(2 ,1)
(3 ,1)
(4 ,1)
(5 ,1)
(5 ,2)
(6 ,2)
(6 ,1)
(7 ,1)
(7 ,2)
(7 ,3)
(6 ,3)
(6 ,4)
(5 ,4)
(5 ,5)
(5 ,6)
(4 ,6)
(4 ,7)
(4 ,8)
(5 ,8)
(6 ,8)
(6 ,7)
(7 ,7)
(7 ,8)
(8 ,8)
对比:
两种写法相比之下,用bfs的搜索方式能够找到最短的路径,用dfs能够找到所有的路径。就复杂度而言,bfs更优一些。
例题:
迷宫问题是学习栈和队列的经典例题,这里可以参考poj-3984
题目链接