C++ 迷宫问题的回溯解法

// DataStruTest1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 
#include
using namespace std;

struct offsets{
	int a;
	int b;
	char * dir;
};

const offsets moves[8] = {{-1,0,"北"},{-1,1,"东北"},{0,1,"东"},{1,1,"东南"},{1,0,"南"},{1,-1,"西南"},{0,-1,"西"},{-1,-1,"西北"}};
const int m=5,n=6;
int Maze[m+2][n+2] = {    1,1,1,1,1,1,1,1,
	                                       0,0,0,1,1,1,0,1,
	                                       1,1,1,0,1,1,0,1,
	                                       1,0,0,0,1,0,1,1,
	                                       1,1,1,0,0,1,0,1,
	                                       1,1,0,1,0,1,0,0,
	                                       1,1,1,1,1,1,1,1  };
int mask[m+2][n+2] = {0};
stack  paths;

bool SeekPathRecurse(int x , int y);
bool SeekPathNoRecurse(int x=1 , int y=1);

int _tmain(int argc, _TCHAR* argv[])
{
	//Use the recurse method.
	for(int i=0;i mystack;
	offsets tmpoff;
	int s,t,p,q;
	int d;
	char * dir;
	tmpoff.a = 1;
	tmpoff.b = 1;
	tmpoff.dir = "东";
	mystack.push(tmpoff);
	while(mystack.empty()==false)
	{
		tmpoff = mystack.top();
		mystack.pop();
		s = tmpoff.a;
		t = tmpoff.b;
		d=2;
		while(d<8)
		{
			p = s+moves[d].a;
			q = t+moves[d].b;
			dir = moves[d].dir;
			if(p==m && q==n)
			{
				//这里是输出结果,mystack里面存储的是倒序的路径
				stack tmpstack;
				while(mystack.empty()==false)
				{
					offsets tmpMove = mystack.top();
					mystack.pop();
					tmpstack.push(tmpMove);
				}
				//所以需要用另外一个栈进行逆序一下输出
				while(tmpstack.empty()==false)
				{
					offsets tmpMove = tmpstack.top();
					tmpstack.pop();
					cout<<"("<


结果如下:

 

 

你可能感兴趣的:(算法与数据结构)