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 //else 19 //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 }