如图是一个矩形迷宫,需要从起点(1,1)走到终点(4,3),那么需要7步。
下面程序完成从起点(0,1)到终点(0,3)的最短距离,结果为12.
#include <stdio.h>
using namespace std;
struct Position
{
Position(int row, int col)
{
x = row;
y = col;
}
int x;
int y;
Position& operator = (Position& p)
{
x = p.x;
y = p.y;
return *this;
}
bool operator == (Position& p)
{
return x == p.x && y == p.y;
}
};
enum Direction
{
Left,
Right,
Up,
Down
};
Position NextPosition(Position pNow, Direction dMove)
{
Position pTarget = pNow;
switch (dMove)
{
case Left:
pTarget.y--;
break;
case Right:
pTarget.y++;
break;
case Up:
pTarget.x--;
break;
case Down:
pTarget.x++;
break;
default:
break;
}
return pTarget;
}
const int ROW = 5;
const int COL = 4;
int MazeMap[ROW][COL] = {
0,0,1,0,
0,0,1,0,
0,0,1,0,
0,1,0,0,
0,0,0,1
};
bool book[ROW][COL] = { false };
int MinPath = 999999;
void dfs(Position p, int iTotalStep)
{
Position pEnd(0, 3);
if (pEnd == p)
{
if (iTotalStep < MinPath)
{
MinPath = iTotalStep;
}
return;
}
for (int i=0; i<=Down; i++)
{
Position pTarget = NextPosition(p, (Direction)i);
if (pTarget.x <0 || pTarget.y <0 || pTarget.x >= ROW || pTarget.y >= COL)
{
continue;
}
if (MazeMap[pTarget.x][pTarget.y] == 0 && !book[pTarget.x][pTarget.y])
{
book[pTarget.x][pTarget.y] = true;
dfs(pTarget, iTotalStep + 1);
book[pTarget.x][pTarget.y] = false;
}
}
return;
}
int main()
{
Position pStart(0,1);
book[0][0] = 1;
dfs(pStart, 0);
printf("Shortest path length is %d.", MinPath);
}