Graph traversal (bfs + dfs) template, bfsdfs

Source: Internet
Author: User

Graph traversal (bfs + dfs) template, bfsdfs

Bfs

 1 #include<iostream> 2 #include<queue> 3 #include<cstdio>  4 using namespace std; 5 queue<int>q; 6 int map[1001][1001]; 7 int vis[1001]; 8 int n,m; 9 void bfs(int p)10 {11     q.push(p);12     vis[p]=1;13     printf("%c-->",char(q.front()+64));14     while(q.size()!=0)15     {    16         int k=q.front();17         q.pop();18         for(int i=1;i<=n;i++)19         {20             21             if(vis[i]==0&&map[k][i]==1)22             {23                 printf("%c-->",char(i+64));24                 //q.pop();25                 q.push(i);26                 vis[i]=1;27             }28         }29     }30 }31 int main()32 {33     34     scanf("%d%d",&n,&m);35     for(int i=1;i<=m;i++)36     {37         char x,y;38         //scanf("\n%d %d",&x,&y);39         cin>>x>>y;40         x=x-64;41         y=y-64;42         map[x][y]=map[y][x]=1;43     }44     bfs(1);45     return 0;46 }

Dfs

 1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 int map[1001][1001]; 5 int vis[1001]; 6 int n,m; 7 void dfs(int p) 8 { 9     vis[p]=1;10     printf("%c --> ",char(p+64));11     for(int i=1;i<=n;i++)12     {13         if(vis[i]==0&&map[p][i]==1)14         {15         16             dfs(i);17         }18         //else19         //return ;20     }21 }22 int main()23 {24     25     scanf("%d%d",&n,&m);26     for(int i=1;i<=m;i++)27     {28         char x;29         char y;30         scanf("\n%c %c",&x,&y);31         //cin>>x>>y;32         x=x-64;33         y=y-64;34         map[x][y]=map[y][x]=1;35     }36     dfs(1);37     return 0;38 }

 

Related Article

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.