Graph traversal BFS

Source: Internet
Author: User
| Help center | welcome, liang530, office call: 0738-8371676
  • Homepage

    You are welcome to visit the Program Design Competition website of Hunan Institute of humanities and technology. We are striving to do better!
  • System Homepage
    | Help |
    Full-text search
  • Discussion board
    | Forum list
  • Question list
    | Upload questions
    | Submission status
  • The competition is over
    |
    Reserve a competition |
    Current competition
  • User ranking
    | Modify personal information
    | User Registration
Data Structure: Figure 2 (BFS traversal)Time limit (Common/Java): 1000 ms/3000 Ms running memory limit: 65536 Kbyte
Total submitted: 36 tested: 22

Description

Starting from a vertex in a given connected graph, all vertices in the graph are accessed along some edges, and each vertex is accessed only once. This is called graph traversal. Graph traversal involves two types: DFS and BFS.

In the figure above, starting from vertex 0, the traversal order is 0 1 4 8 2 5 3 6 7 according to the sequence BFS of vertex numbers from small to large.

Input

Enter the number of vertices and edges of the graph and the two vertices of each edge.

Output

BFS traversal order.

Sample Input

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

Sample output

0 1 4 8 2 5 3 6 7

Question Source

Hnldyhy

[Submit] [submit status] [Forum]

| Return |
Go to the page header |

 

 

 

 

#include <iostream>#include <queue>using namespace std;queue <int> my;int m,n,map[100][100],bz[100],g=0;void BFS(int k){   int t,i;    my.push(k);    bz[k]=1;    while(!my.empty())    {        t=my.front();g++;        my.pop();        if(g!=m)cout<<t<<" "; else cout<<t<<endl;        for(i=0;i<m;i++)            if(map[t][i]==1&&bz[i]==0)            {                bz[i]=1;                my.push(i);            }    }}int main(){    int i=0,n,x,y,ans;    cin>>m>>n;    while (i<n)    {       cin>>x>>y;       map[x][y]=map[y][x]=1;       i++;    }    BFS(0);    return 0;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.