您的位置:首页 > 其它

nyoj-58-最小步数

2013-07-19 09:38 232 查看
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#define L 9
using namespace std;
bool 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 num[9][9],dx[4]={1,0,-1,0},dy[4]={0,1,0,-1},dis[81],temp[9][9];//num数组存放到某一点的最小步数,dis为队列,temp标记是否访问过
int bfs(int x1,int y1,int x2,int y2);
int main()
{
int n,a,b,c,d;
scanf("%d",&n);
while(n--)
{
scanf("%d%d%d%d",&a,&b,&c,&d);
printf("%d\n",bfs(a,b,c,d));
}
return 0;
}

int bfs(int x1,int y1,int x2,int y2)
{
memset(num,0,sizeof(num));
memset(temp,0,sizeof(temp));
int l=0,r=0,t;
t=x1*L+y1;
dis[r++]=t;
temp[x1][y1]=1;
num[x1][y1]=0;
while(l<r)
{
t=dis[l++];
int x,y,bx,by;
x=t/L;y=t%L;
for(int i=0;i<4;i++)
{
bx=x+dx[i];by=y+dy[i];
if(temp[bx][by]==0&&bx>=0&&bx<L&&by>=0&&by<L&&map[bx][by]==0)
{
dis[r++]=bx*L+by;
num[bx][by]=num[x][y]+1;
temp[bx][by]=1;
}
}
}
return num[x2][y2];
}


此题用广搜 打出步数表 然后输出 其实可以在找到这点后就可以跳出了 没必要全循环完的我的第一次广搜代码 见谅啊 各位
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: