fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int> ke[1001];
  4. int m , n;
  5. int parent[1001];
  6. bool visited[1001];
  7. int kt = 0;
  8. void DFS(int u) {
  9. visited[u] = true;
  10. for (int x : ke[u]) {
  11. if (!visited[x]) {
  12. cout << x << " ";
  13. parent[x] = u;
  14. DFS(x);
  15. kt = x; // C?p nh?t bi?n kt m?i khi tìm th?y m?t d?nh chua du?c tham
  16. }
  17. }
  18. }
  19. void BFS(int u){
  20. queue<int> q;
  21. q.push(u);
  22. visited[u] = true;
  23. while(!q.empty()){
  24. int x = q.front(); q.pop();
  25. for(int y : ke[x]){
  26. if(!visited[y]){
  27. cout << y << " ";
  28. q.push(y);
  29. visited[y] = true;
  30. }
  31. }
  32. }
  33. }
  34.  
  35. int main(){
  36. cin >> m >> n ;
  37. int s;
  38. cin >> s;
  39. for(int i = 1 ; i <= n ; i++){
  40. int x,y;
  41. cin >> x >> y;
  42. ke[x].push_back(y);
  43. ke[y].push_back(x);
  44. }
  45. for(int i = 1 ; i <= n ; i++){
  46. sort(ke[i].begin(),ke[i].end());
  47. }
  48. cout << s << " ";
  49. BFS(s);
  50.  
  51. }
Success #stdin #stdout 0.01s 5304KB
stdin
5 7 5
4 1
5 3

4 3
5 1
3 2
4 2
2 1
stdout
5 1 3 2 4