给出一个迷宫,求解从路口到出口的全部路径是一个经典问题,C++实现代码如下:
// Algrithm_Practice.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
using namespace std;
#define D 10 //迷宫的维度
#include<iostream>
#include<stack>
int maze[D][D] = { //迷宫,0代表障碍,1代表可行
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 0, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 0, 1, 1, 1, 1, 0, 0, 1, 1, 0 },
{ 0, 1, 0, 0, 0, 1, 1, 1, 1, 0 },
{ 0, 1, 1, 1, 0, 1, 1, 1, 1, 0 },
{ 0, 1, 0, 1, 1, 1, 0, 1, 1, 0 },
{ 0, 1, 0, 0, 0, 1, 0, 0, 1, 0 },
{ 0, 0, 1, 1, 1, 1, 1, 1, 1, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
int mark[D][D] = {0};
struct PosType{ //迷宫的坐标
int x;
int y;
};
struct ElemType{
int step;
PosType pos;
int di; //在这一位置时的决策
};
void printStack(stack<ElemType> s){ //打印路径
stack<ElemType> temp;
while (!s.empty()){
ElemType e = s.top();
temp.push(e);
s.pop();
}
while (!temp.empty()){
temp.pop();
}
}
bool Ismark(PosType pos){ //该位置是否在路径中
if (mark[pos.x][pos.y] == 1)
return true;
return false;
}
bool CanPass(PosType pos){ //该位置是否可行
if (pos.x > 9 || pos.x<0 || pos.y>9 || pos.y < 0)
return false;
if (maze[pos.x][pos.y] == 0)
return false;
if (!Ismark(pos))
return true;
return false;
}
void FootPrint(PosType pos){ //足迹标记
mark[pos.x][pos.y] = 1;
}
PosType NextPos(PosType pos, int i){ //待转移的位置
if (i == 1){
int x = pos.x + 1;
int y = pos.y;
PosType temp = { x, y };
return temp;
}
else if (i == 2){
int x = pos.x;
int y = pos.y+1;
PosType temp = { x, y };
return temp;
}
else if (i == 3){
int x = pos.x - 1;
int y = pos.y;
PosType temp = { x, y };
return temp;
}
else if (i == 4){
int x = pos.x ;
int y = pos.y-1;
PosType temp = { x, y };
return temp;
}
}
void MazePath(PosType start, PosType end){
stack<ElemType> path;
PosType curpos = start;
int curstep = 1;
do{
if (CanPass(curpos)){
FootPrint(curpos);
ElemType e = { curstep, curpos, 1 }; //将该位置保留,并记录在该步位移方向
path.push(e);
if (curpos.x == end.x&&curpos.y==end.y){
printStack(path);
cout << endl;
exit(0);
}
curpos = NextPos(curpos, 1);
curstep++;
}
else{
if (!path.empty()){
ElemType e = path.top();
path.pop();
while (e.di == 4 && !path.empty()){
cout << e.pos.x << "," << e.pos.y << endl;
FootPrint(e.pos);
e = path.top();
path.pop();
}
if (e.di < 4){
e.di++;
path.push(e);
curpos = NextPos(e.pos, e.di);
}
}
}
} while (!path.empty());
}
int _tmain(int argc, _TCHAR* argv[])
{
PosType start = { 1, 1 };
PosType end = { 8, 8 };
MazePath(start, end);
return 0;
}
特别需要注意的一点是,C++中bool型函数很容易忽略返回值,C++编译器不会报告错误!