BFS总结
BFS:找到的路径长度一定是起点到终点的最短路径
构思BFS的步骤:
1、确定队列结构体要记录什么东西,一般为x,y坐标,累加的路径长度r
2、确定入队条件
3、确定终结条件
模板:
int map[M][M],wan[M][M]; //map是图;wan是弯的数量,主要用来剪枝 int go[4][2]= {{-1,0},{1,0},{0,-1},{0,1}}; //go表示走上、下、左、右方向 struct node { int x,y,turn,road; node() {} node(int a,int b,int c,int d) //构造函数 { x=a; y=b; turn=c; road=d; } }; bool bfs() { for(int i=1; i<=R; ++i) //初始化wan for(int j=1; j<=C; ++j) wan[i][j]=inf; queue<node> Q; node f(s_x,s_y,-1,6); //入队的首元素 Q.push(f); while(!Q.empty()&&!F) { node s=Q.front(); Q.pop(); for(int i=0; i<4; ++i) { int nx=s.x+go[i][0]; int ny=s.y+go[i][1]; if(nx<1||nx>R||ny<1||ny>C||map[nx][ny]!=0||t>2||t>wan[nx][ny]) //入队条件 continue; wan[nx][ny]=t; node p(nx,ny,t,i); Q.push(p); //满足以上苛刻条件的点入队 } } } 附加优先队列: struct node { friend bool operator< (node n1, node n2) //按照priority从大到小排列 { return n1.priority < n2.priority; //important } int priority; int value; }; priority_queue<node> Q;
A*
struct point { int x,y; int sum,yu; friend bool operator<(point a,point b) { return a.sum+a.yu>b.sum+b.yu; } point(int a,int b,int c) { x=a;y=b;sum=c; yu=abs(ei-a)+abs(ej-b); } }; int afs(int x,int y) { priority_queue<point> Q; point f(x,y,0); Q.push(f); while(!Q.empty()) { point t=Q.top(); Q.pop(); for(int i=0;i<4;i++) { int nx=t.x+go[i][0]; int ny=t.y+go[i][1]; if(nx<0||nx>=h||ny<0||ny>=w) continue; if(ma[nx][ny]=='#') continue; int temp=re[t.x][t.y]+1; if(ma[nx][ny]=='@') temp+=d; if(temp>=re[nx][ny]&&re[nx][ny]>=0) continue; point next(nx,ny,temp); re[nx][ny]=temp; Q.push(next); if(nx==ei&&ny==ej) return re[ei][ej]+1; } } return re[ei][ej]+1; }