hdu1026广搜

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;

class P
{
public:	
	char mark;
	int record; //搜索过这里没 
	int x,y;
	vector<int> XX;
	vector<int> YY;
	P()
	{
		record=0; //0代表没有
	}
	void wait()
	{
		mark-=1;
		XX.push_back(x);
		YY.push_back(y);
	}
	void show()
	{
		printf("It takes %d seconds to reach the target position, let me show you the way.\n",XX.size());
		int TIME=1;
		for(int i=0;i<XX.size();i++)
		{
			if(i==0)
			{
				printf("%ds:(%d,%d)->(%d,%d)\n",TIME++,0,0,XX[0],YY[0]);
				
			}
			else
			{
				if(XX[i-1]!=XX[i] || YY[i-1]!=YY[i])
				printf("%ds:(%d,%d)->(%d,%d)\n",TIME++,XX[i-1],YY[i-1],XX[i],YY[i]);
				else
				{
					printf("%ds:FIGHT AT (%d,%d)\n",TIME++,XX[i],YY[i]);
				}
			}
		}
		printf("FINISH\n");
	}
	void add(P& po)
	{
		for(int i=0;i<po.XX.size();i++)
		{
			XX.push_back(po.XX[i]);
			YY.push_back(po.YY[i]);
		}
		XX.push_back(x);
		YY.push_back(y);
		record=1;
		po.record=1;
	}
	friend void operator>>(istream &in,P& point)
	{
		in>>point.mark;
		
	    point.record=0; //搜索过这里没 
		point.XX.clear();
		point.YY.clear();
	}
	friend ostream& operator<<(ostream &out,P point)
	{
		out<<point.mark;
		return out;
	}
	void operator=(char c)
	{
		this->mark=c;
	}
	void operator=(P po)
	{
		this->mark=po.mark;
		this->record=po.record; 
		this->x=po.x;
		this->y=po.y;
		XX.assign(po.XX.begin(),po.XX.end());
		YY.assign(po.YY.begin(),po.YY.end());
	}
	void dirty() //脏了这里 
	{
		this->record=1;
	}
};
P map[105][105];
queue<P> Q;
int N,M;
int arrow[2][4]={1,-1,0,0,
				 0,0,1,-1};
void BFS()
{
	while(Q.size()>0)Q.pop();
	Q.push(map[0][0]);
	map[0][0].dirty();
	int TIME=0;
	int amount;
	P pp;
	while(1)
	{
		if(TIME++>=9)break;//连续9次没有前进了 说明路都堵住了
		amount=Q.size();
		while(amount--)
		{
			pp=Q.front();
			Q.pop();
			if(pp.mark!='.' && pp.mark!='0')
			{
				pp.wait();
				if(pp.x==N-1 && pp.y==M-1 &&pp.mark=='0')
				{
					pp.show();
					return;
				}
				Q.push(pp);
				continue;
			}
			for(int i=0;i<4;i++)
			{
				int x=pp.x+arrow[0][i];
				int y=pp.y+arrow[1][i];
				if(x<0 || x>N || y<0 || y>M)continue;
				if(map[x][y].record==1)continue;
				if(map[x][y].mark=='X')continue;
				map[x][y].add(pp);
				Q.push(map[x][y]);
				TIME=0;
				if(x==N-1 && y==M-1 &&  map[x][y].mark=='.')
				{
					map[x][y].show();
					return;
				}
			}
		}
		
	}
	cout<<"God please help our poor hero.\nFINISH"<<endl;
}
int main()
{
	//freopen("in.txt","r",stdin);
	while(cin>>N>>M)
	{
		for(int i=0;i<N;i++)
		{
			for(int j=0;j<M;j++)
			{
				cin>>map[i][j];
				map[i][j].x=i;
				map[i][j].y=j;
			}
		}
		BFS();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/artistkeepmonkey/article/details/88081051
今日推荐