几个月前ac的,今天再次写,发现很多细节任然把握不好,总结到了学过的东西真的要多看,不然忘记的真的会很多的,同时发现自己写的代码真的烂到极点了,加油;
bfs:
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#include<stdio.h>
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 dirx[]={0,1,0,-1};
int diry[]={1,0,-1,0};
int sx,sy,ex,ey;
int countt;
typedef struct point
{
int x,y;
}POINT;
queue<POINT>q;
bool visit[9][9];
void bfs()
{
POINT temp;
temp.x=sx;
temp.y=sy;
q.push(temp);
visit[sx][sy]=false;
POINT tt[100];
while(!q.empty())
{
int v=0;
while(!q.empty())
{
tt[v]=q.front();
q.pop();
v++;
} //这里我是把队列里面的全部转到数组中去,本代码的后面我参考别人的代码再写了一遍
countt++;
while(v--)
{
POINT temp2;
temp2=tt[v];
if(temp2.x==ex&&temp2.y==ey){
cout<<countt-1<<endl;
return ;
}
for(int i=0;i<4;i++)
{
int x=temp2.x+dirx[i];
int y=temp2.y+diry[i];
if(visit[x][y]&&!map[x][y]&&x>=0&&x<=8&&y>=0&&y<=8)
{
POINT temp3;
temp3.x=x;
temp3.y=y;
q.push(temp3);
visit[x][y]=false;
}
}
}
}
}
int main()
{
int times;
cin>>times;
while(times--)
{
countt=0;
cin>>sx>>sy>>ex>>ey;
memset(visit,true,sizeof(visit));
bfs();
while(!q.empty()){
q.pop();
}
}
}
参考大神后的代码后再写的bfs:
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#include<stdio.h>
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 dirx[]={0,1,0,-1};
int diry[]={1,0,-1,0};
int sx,sy,ex,ey;
int countt;
typedef struct point
{
int x,y,step;
}POINT;
queue<POINT>q;
bool visit[9][9];
void bfs()
{
POINT temp;
temp.x=sx;
temp.y=sy;
temp.step=0;
q.push(temp);
visit[sx][sy]=false;
while(!q.empty())
{
POINT temp2;
temp2=q.front();
q.pop();
if(temp2.x==ex&&temp2.y==ey){
cout<<temp2.step<<endl;
return ;
}
for(int i=0;i<4;i++)
{
int x=temp2.x+dirx[i];
int y=temp2.y+diry[i];
if(visit[x][y]&&!map[x][y]&&x>=0&&x<=8&&y>=0&&y<=8)
{
POINT temp3;
temp3.x=x;
temp3.y=y;
temp3.step=temp2.step+1;
q.push(temp3);
visit[x][y]=false;
}
}
}
}
int main()
{
int times;
cin>>times;
while(times--)
{
countt=0;
cin>>sx>>sy>>ex>>ey;
memset(visit,true,sizeof(visit));
bfs();
while(!q.empty()){
q.pop();
}
}
}
为了提高自己的深搜,于是我又再写了一遍: