欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

BFS 框架

程序员文章站 2022-05-20 20:24:24
...
#include <iostream>
#include <stdio.h>
#include <queue>
#include<cstring>
#include<cmath>
#define MAX_N 105
#define MAX_M 105
using namespace std;
typedef pair<int,int> p;
char maze[MAX_N][MAX_M+1];//保存地图坐标
int d[MAX_N][MAX_M];//保存走到每个点的距离
int N,M;//地图大小
int sx,sy; 
int gx,gy; 
int dx[4]= {1,0,-1,0},dy[4]= {0,1,0,-1};//方向向量
void bfs() { //bfs函数
	queue<p> q;
	memset(d,-1,sizeof(d));
	q.push(p(sx,sy));//把起点压入队列 
	d[sx][sy]=0;//起点初始化 
	while(q.size()) {
		p pp=q.front();
		q.pop();
		if(pp.first==gx&&pp.second==gy) {        
			……//返回 
		}
		for(int i=0; i<4; i++) {
			int nx=pp.first+dx[i];
			int ny=pp.second+dy[i];
			if(……) {//判断条件 
				q.push(p(nx,ny));
				d[nx][ny]=d[pp.first][pp.second]+1;//步数加一 
			}
		}
	}
}
int main() {
	…… 
	return 0;
}
相关标签: bfs