深度优先搜索算法解迷宫问题

 如图是一个矩形迷宫,需要从起点(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);
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值