pursuit的专栏

如果一个人不愿意在平静中度过一生,就要像雄鹰一样忍住孤独,背负青天,傲然飞翔,以独特的眼力和胆略审视这个世界,用清晰而坚定的智慧眼光捕捉任何一个成功的机遇。...

http://acm.nyist.net/JudgeOnline/problem.php?pid=58

bfs搜索水题进行时~~~~

#include<iostream>
#include<string.h>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
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
};
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct point
{
	int x;
	int y;
	int step;
}po;
bool visit[10][10];
int sx,sy,ex,ey;
int step;
int bfs(int x,int y)
{
	memset(visit,false,sizeof(visit));
	queue<point>q;
	po.x=x;po.y=y;po.step=0;
	q.push(po);
	visit[x][y]=true;
	while(!q.empty())
	{
		po=q.front();
		q.pop();
		x=po.x;y=po.y;step=po.step;
		if(x==ex&&y==ey) return step;
		for(int i=0;i<4;++i)
		{
			int x1=x+dx[i];
			int y1=y+dy[i];
			if(!map[x1][y1]&&!visit[x1][y1]&&x1>=0&&x1<=8&&y1>=0&&y1<=8)
			{ po.x=x1;po.y=y1;po.step=step+1;q.push(po);
			  visit[x1][y1]=true;
			}
		}
	}
}
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		cin>>sx>>sy>>ex>>ey;
		cout<<bfs(sx,sy)<<endl;
	}return 0;
}

dfs

#include<iostream>
#include<string.h>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
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
};
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct point
{
	int x;
	int y;
	int step;
}po;
int sx,sy,ex,ey;
int step,minstep;
void dfs(int x,int y)
{
	if(x==ex&&y==ey) {minstep=min(step,minstep);return;}//结束条件
	 for(int i=0;i<4;++i)
	{
		int x1=dx[i]+x;
		int y1=dy[i]+y;
		if(x1>=0&&x1<=8&&y1>=0&&y1<=8&&!map[x1][y1])
		{
			step++;
			map[x1][y1]=1;
			dfs(x1,y1);
			map[x1][y1]=0;//回溯。。。。
			step--;
		}
	}
}
int main()
{
	int T;
    scanf("%d",&T);
	while(T--)
	{    step=0;
	     minstep=0xffffff;
		scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
		map[sx][sy]=1;
		dfs(sx,sy);
		map[sx][sy]=0;
		printf("%d\n",minstep);
	}return 0;
}



阅读更多
文章标签: struct
个人分类: 搜索 ACM算法
上一篇http://acm.nyist.net/JudgeOnline/problem.php?pid=27
下一篇简单的排列组合题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭