ppt 圖的基本演算法 Bfs

來源:互聯網
上載者:User

標籤:blog   http   使用   io   for   2014   amp   演算法   

 

 

 

 

 

 

 

 

輸入:

8 9
1 2
1 3
2 4
2 5
3 6
3 7
4 8
5 8
6 7

 

 

 

 

 

// 圖的BFS,使用C++隊列
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
#define N 10
int g[N][N],bz[N],n,m;
queue <int> q;
void BFS(int cur)
{ int j;
bz[cur]=1; q.push(cur);
while (!q.empty())
{ cur=q.front(); printf(" V%d ", cur);q.pop();
for (j=1;j<=N;j++)
if (bz[j]==0 && g[cur][j]==1) { q.push(j); bz[j]=1; }
}
}
void input()
{ int i,j,f,t;
scanf("%d%d",&n,&m);
for (int i=1; i<=m; i++)
{ scanf("%d%d",&f,&t); g[f][t]=g[t][f]=1; }
}
int main()
{ memset(g,0,sizeof(g)); memset(bz,0,sizeof(bz));
input(); BFS(1);
}

 

*************************************************************************************

 


// 圖的BFS
#include <stdio.h>
#include <string.h>
#define N 10
int g[N][N],bz[N],n,m,q[N],qe,qs;
void BFS(int cur)
{ int j,qs,qe;
qs=qe=0; bz[cur]=1; q[qe++]=cur;
while (qs<qe)
{ cur=q[qs++]; printf(" V%d ", cur);
for (j=1;j<=N;j++)
{ if (bz[j]==0 && g[cur][j]==1)
{ q[qe++]=j; bz[j]=1; }
}
}
}
void input()
{ int i,j,f,t;
scanf("%d%d",&n,&m);
for (int i=1; i<=m; i++)
{ scanf("%d%d",&f,&t); g[f][t]=g[t][f]=1; }
}
int main()
{ int i,j;
memset(g,0,sizeof(g)); memset(bz,0,sizeof(bz));
input(); BFS(1);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.