今天做到了bfs的练习,顺便写下心得。。。
bfs能解决搜索和最短路径的问题。
下面是学习心得:
typedef struct point //定义点
{
int x;
int y;
}P;
bfs()
{
int level[N]; //记录队列中元素层数,即从起点到该点最短路径距离
P father[NX][NY],queue[N]; //father用来记录父节点,queue用来记录队列
int top=0; //top用来记录队列长度,并指向最后节点
for(int i=0;i<nx;i++)
for(int j=0;j<ny;j++)
{
father[i][j].x=-1; //初始化father
father[i][j].y=-1;
}
queue[top].x=x0; //对起点进行赋值
queue[top].y=y0;
father[x0][y0].x=x0;
father[x0][y0].y=y0;
top++;
for(int i=0;i<top;i++)
{
for(遍历第i个元素的邻接点)
{
if(邻接点没标记) //若邻接点father为-1
{
父节点记为第i个元素;
queue[top]赋值为该邻接点; //把元素接到队列上
level[top]=level[i]+1; //元素层次为父节点层次+1
top++; //队列长度+1
}
if(邻接点满足条件)
{
return ...;
}
}
}
}
上一道训练题:
#include<stdio.h>
#include<string.h>
int dx[8]={-1,-1,-2,-2,1,1,2,2}; //对应的xy变化表
int dy[8]={2,-2,1,-1,2,-2,1,-1};
typedef struct point
{
int x;
int y;
}P;
int bfs(char* s1,char* s2)
{
int x1=(int)(s1[0]-'a'+1); //转化为数字
int x2=(int)(s2[0]-'a'+1);
int y1=(int)(s1[1]-'0');
int y2=(int)(s2[1]-'0');
int level[80],top=0,flag; //top用来记录队列长度,并可用于指向队尾
P father[10][10],queue[80]; //father记录父节点,queue记录队列
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
{
father[i][j].x=-1; //父节点初始化为-1
father[i][j].y=-1;
}
level[top]=0;
father[x1][y1].x=x1;
father[x1][y1].y=y1;
queue[top].x=x1;
queue[top++].y=y1;
if(x1==x2&&y1==y2)
return 0;
for(int i=0;i<top;i++)
{
flag=0;
for(int j=0;j<8;j++) //标记所有邻接点
{
int tempx,tempy;
tempx=queue[i].x+dx[j];
tempy=queue[i].y+dy[j];
if(tempx<=8&&tempx>0&&tempy<=8&&tempy>0&&father[tempx][tempy].x==-1)
{
father[tempx][tempy].x=queue[i].x;
father[tempx][tempy].y=queue[i].y;
queue[top].x=tempx;
queue[top].y=tempy;
level[top++]=level[i]+1; //level用来记录当前元素层次
}
if(tempx==x2&&tempy==y2)
{
flag=1;
break;
}
}
if(flag==1)
return level[top-1];
}
}
int main()
{
char s1[3],s2[3];
int num;
while(scanf("%s%s",s1,s2)!=EOF)
{
num=bfs(s1,s2); //输入
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,num);
}
return 0;
}