您的位置:首页 > 其它

【深度搜索】NYOJ58最小步数

2014-05-14 16:30 204 查看
题目来源:http://acm.nyist.net/JudgeOnline/problem.php?pid=58

这道题也还是一道很简单的深度搜索的问题,利用队列+深搜很容易写出来。

#include <iostream>
#include <queue>

using namespace std;

struct node
{
	int x,y,step;
};

int dir[4][2]={-1,0,0,1,1,0,0,-1};
int v[9][9];

int bfs(node s,node t,int map[9][9])
{
	queue<node> Q;
	int i;
	node temp;
	Q.push(s);
	while(1)
	{
		if(s.x==t.x && s.y==t.y)
			return s.step;
		for(i=0;i<4;i++)
		{
			temp.x=s.x+dir[i][0];
			temp.y=s.y+dir[i][1];
			if(map[temp.x][temp.y]==0)
			{
				temp.step=s.step+1;
				map[temp.x][temp.y]=1;
				Q.push(temp);
			}
		}
		s=Q.front();
		Q.pop();
	}
	
}

int main()
{
	int T;
	node start,end;
	cin>>T;
	while(T--)
	{
		int map[9][9]={  
			1,1,1,1,1,1,1,1,1,  
			1,0,0,1,0,0,1,0,1,  
			1,0,0,1,1,0,0,0,1,  
			1,0,1,0,1,1,0,1,1,  
			1,0,0,0,0,1,0,0,1,  
			1,1,0,1,0,1,0,0,1,  
			1,1,0,1,0,1,0,0,1,  
			1,1,0,1,0,0,0,0,1,  
			1,1,1,1,1,1,1,1,1  
		};//题目中的数据 	
		cin>>start.x>>start.y>>end.x>>end.y;
		start.step=0;
		map[start.x][start.y]=1;
		cout<<bfs(start,end,map)<<endl;
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: