c++解决迷宫寻路问题

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

#include "stdafx.h"
#include <iostream>
#include <string>
#include <Windows.h>
#include <list>
using namespace std;
int box[8][10]={{1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,1,0,1,0,1,1,1,1,1},
{1,0,1,0,0,0,0,0,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,1,0,0,1,1,0,0,0,1},
{1,0,1,1,0,0,1,1,0,1},
{1,1,1,1,1,1,1,1,1,1}};
struct sPoint
{
	sPoint(int x1,int y1){x=x1;y=y1;}
	int x;
	int y;
};
void calc(int *box,int width,int height,sPoint start,sPoint end)
{
	list<sPoint> s;
	box[start.x*width+start.y]=2;
	int x=start.x,y=start.y;
	s.push_back(sPoint(x,y));
	while(1)
	{
		if(x==end.x && y==end.y)
		{
			while (!s.empty())
			{
				cout<<s.front().x<<"  "<<s.front().y<<endl;
				s.pop_front();
			}
			break;
		}
		else
		{
			//cout<<x<<"  "<<y<<endl;
		}
		bool bGo=false;
		for(int i=0;i<8;i++)
		{
			switch(i)
			{
			case 0:
				{
					if(y>0 && box[(y-1)*width+x]==0)
					{
						y=y-1;
						box[y*width+x]=2;
						s.push_back(sPoint(x,y));
						bGo=true;
					}
					break;
				}
			case 1:
				{
					if(x<width-1 && y>0 && box[(y-1)*width+x+1]==0)
					{
						x=x+1;
						y=y-1;
						box[y*width+x]=2;
						s.push_back(sPoint(x,y));
						bGo=true;
					}
					break;
				}
			case 2:
				{
					if(x<width-1 && box[y*width+x+1]==0)
					{
						x=x+1;
						box[y*width+x]=2;
						s.push_back(sPoint(x,y));
						bGo=true;
					}
					break;
				}
			case 3:
				{
					if(x<width-1 && y<height-1 && box[(y+1)*width+x+1]==0)
					{
						x=x+1;
						y=y+1;
						box[y*width+x]=2;
						s.push_back(sPoint(x,y));
						bGo=true;
					}
					break;
				}
			case 4:
				{
					if(y<height-1 && box[(y+1)*width+x]==0)
					{
						y=y+1;
						box[y*width+x]=2;
						s.push_back(sPoint(x,y));
						bGo=true;
					}
					break;
				}
			case 5:
				{
					if(x>0 && y<height-1 && box[(y+1)*width+x-1]==0)
					{
						x=x-1;
						y=y+1;
						box[y*width+x]=2;
						s.push_back(sPoint(x,y));
						bGo=true;
					}
					break;
				}
			case 6:
				{
					if(x>0 && box[y*width+x-1]==0)
					{
						x=x-1;
						box[y*width+x]=2;
						s.push_back(sPoint(x,y));
						bGo=true;
					}
					break;
				}
			case 7:
				{
					if(x>0 && y>0 && box[(y-1)*width+x-1]==0)
					{
						x=x-1;
						y=y-1;
						box[y*width+x]=2;
						s.push_back(sPoint(x,y));
						bGo=true;
					}
					break;
				}
			}
			if(bGo)
			{
				break;
			}
		}
		if(!bGo)
		{
			if(s.size()>0)
			{
				sPoint p=s.back();
				s.pop_back();
				x=p.x;
				y=p.y;
			}else
			{
				cout<<"error"<<endl;
				break;
			}
			
		}
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	calc((int*)box,10,8,sPoint(1,1),sPoint(8,6));
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值