您的位置:首页 > 其它

bfs模版

2015-08-22 16:12 183 查看
//用队列

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int x1,x2,y2,x3,y3,y1;
int dir[8][2]= {0,1,0,-1,-1,0,1,0,1,1,1,-1,-1,1,-1,-1};
int mark[10][10];
struct nodes
{
int x,y,m;
};
nodes node1,node2;
void bfs()
{
queue<nodes> q;
while(!q.empty())
q.pop();
node1.x=x1;
node1.y=y1;
node1.m=0;
mark[x1][y1]=1;
q.push(node1);
while(!q.empty())
{
node1=q.front();
q.pop();
if(node1.x==x2&&node1.y==y2)
printf("%d\n",node1.m);
for(int i=0; i<8; i++)
{
node2.x=node1.x+dir[i][0];
node2.y=node1.y+dir[i][1];
if(node2.x>=1&&node2.x<=8&&node2.y>=1&&node2.y<=8&&!mark[node2.x][node2.y])
{
mark[node2.x][node2.y]=1;
node2.m=node1.m+1;
q.push(node2);
}
}
}

}
int main()
{
int k=0;
while(~scanf("%d%d%d%d%d%d",&x1,&y1,&x2,&y2,&x3,&y3))
{
k++;
memset(mark,0,sizeof(mark));
mark[x3][y3]=1;
printf("Case %d: ",k);
bfs();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: