您的位置:首页 > 理论基础 > 数据结构算法

数据结构——图的广度优先搜索模板

2017-10-03 09:25 344 查看
const int maxn=1000;
const int inf=1e9;

//邻接矩阵版
int n,G[maxn][maxn];
bool inq[maxn]={false};

void bfs(int u){
queue<int> q;
q.push(u);
inq[u]=true;
while(!q.empty()){
int u=q.front();q.pop();
for(int v=0;v<n;v++)
if(!inq[v]&&G[u][v]!=inf){
q.push(v);
inq[v]=true;
}
}
}

void bfstrave(){
for(int u=0;u<n;u++)
if(!inq[u]) bfs(u);
}

//邻接表版
vector<int> Adj[maxn];
int n;
bool inq[maxn]={false};

void bfs(int u){
queue<int> q;
q.push(u);
inq[u]=true;
while(!q.empty()){
int u=q.front();q.pop();
for(int i=0;i<Adj[u].size();i++){
int v=Adj[u][i];
if(!inq[v]){
q.push(v);
inq[v]=true;
}
}
}
}

void bfstrave(){
for(int u=0;u<n;u++) if(!inq[u]) bfs(u);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 bfs
相关文章推荐