技術部20170415日集訓

第一題

#include<iostream>
using namespace std;

/*
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
*/

int book[5][5]={0};

int map[5][5];

int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int tx,ty;
/*
void dfs(int x,int y,int step)
{
	if(x==4&&y==4)
	{
		if(min1>step)
		{
			min1=step;
		}
		return;
	}
	for(int i=0;i<4;i++)
	{
		tx=x+next[i][0];
		ty=y+next[i][1];
		if(tx<0||ty<<0||tx>4||ty>4)
		{
			continue;
		}
		if(book[tx][ty]==0&&map[tx][ty]==0)
		{
			book[tx][ty]=1;
			dfs(tx,ty,step+1);
			
			book[tx][ty]=0;
		}
	}
	return ;
}
*/
void print(int x,int y)
{
	cout<<"("<<x<<","<<y<<")"<<endl;
}
typedef struct node
{
	int x;
	int y;
	int step;
	int prestep;
}node;
node que[1000];

void printPath(int num )
{
	if(num!=0)
	{
		printPath(que[num].prestep);
	}

		cout<<"("<<que[num].x<<","<<que[num].y<<")"<<endl;
	
}

void bfs(int x,int y,int step)
{
	for(int i=0;i<5;i++)
	{
		for(int j=0;j<5;j++)
		{
			cin>>map[i][j];
		}
	}
	cout<<"***"<<endl;
	for(int i=0;i<5;i++)
	{
		for(int j=0;j<5;j++)
		{
			cout<<map[i][j]<<" ";
		}
		cout<<endl;
	}
	int head,tail;
	head=tail=0;
	que[tail].x=0;
	que[tail].y=0;
	que[tail].prestep=-1;
	que[tail].step=0;
	tail++;
	book[0][0]=1;
	int flag=0;
	while(head<tail)
	{
		for(int i=0;i<4;i++)
		{
			tx=que[head].x+next[i][0];
			ty=que[head].y+next[i][1];
			if(tx<0||ty<0||tx>4||ty>4)
			{
				continue;
			}
			
			if(book[tx][ty]==0&&map[tx][ty]==0)
			{
				
				que[tail].step=que[head].step+1;
				que[tail].x=tx;
				que[tail].y=ty;
				que[tail].prestep=head;
				book[tx][ty]=1;
				tail++;
			}
			if(tx==4&&ty==4)
			{
				flag=1;
				break;
			}
		}
		if(flag==1)
		{
			break;
		}
		head++;
	}
	
	int res=tail-1;
	printPath(res);
}

int main()
{
	bfs(0,0,0);
	return 0;
}

運行結果:


發佈了74 篇原創文章 · 獲贊 34 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章