分枝限界法求解迷宫问题

#include<stdio.h>
#include<vector>
#include<iostream>
using namespace std;
#define MAXQ 100
#define INF 0x3f3f3f3f
#define MAX_SIZE 21
int H[4]={0,1,0,-1};
int V[4]={-1,0,1,0};
struct Position{
	int x,y;
	Position();
	Position(int i,int j){
		x=i;
		y=j;
	}
};
int n=8;
int m=8;
char Maze[MAX_SIZE][MAX_SIZE]={
};
Position a(0,0),b(n-1,m-1);
int bestlen=INF;
vector<Position>bestpath;
int Count=0;
typedef struct{
	int no;
	Position p;
	int length;
	int pre;
}NodeType;
class QUEUE{
	private:
		NodeType data[MAXQ];
		int front,rear;
	public:
		QUEUE(){
			front=rear=-1;
		}
		bool empty(){
			return front==rear;
		}
		void push(NodeType e){
			rear++;
			data[rear]=e;
		}
		NodeType pop(){
			front++;
			return data[front];
		}
		void GetPath(int s,vector<Position>&path){
			int k=s;
			while(k!=-1){
				path.push_back(data[k].p);
				k=data[k].pre;
			}
		}
};
void solve(){
	NodeType e,e1;
	Position p,p1;
	QUEUE qu;
	e.no=Count++;
	e.pre=-1;
	e.p=a;
	e.length=0;
	qu.push(e);
	while(!qu.empty()){
		e=qu.pop();
		p=e.p;
		if(p.x==b.x&&p.y==b.y){
			if(e.length<bestlen){
				bestlen=e.length;
				bestpath.clear();
				qu.GetPath(e.no,bestpath);
			}
		}else {
			for(int j=0;j<4;j++){
				p1.x=p.x+H[j];
				p1.y=p.y+V[j];
				if(p1.x>=0&&p1.x<n&&p1.y>=0&&p1.y<m&&Maze[p1.x][p1.y]=='O'){
					if(e1.length<bestlen){
						e1.no=Count++;
						e1.length=e.length+1;
						e1.pre=e.no;
						e1.p=p1;
						qu.push(e1);
						Maze[p1.x][p1.y]='K';
					}
				} 
			}
		}
	}
}
int main(){
	solve();
	cout<<bestlen<<endl;
	vector<Position>::reverse_iterator it;
	for(it=bestpath.rbegin();it!=bestpath.rend();it++){
		Maze[it->x][it->y]=' ';
	}
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			if(Maze[i][j]=='K'){
				cout<<"o";
			}else {
				cout<<Maze[i][j];
			}
		}
		cout<<endl;
	}
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值