输入

  1. 5 5 #几个点 几条边
  2. 1 2 #具体边的连接
  3. 1 3
  4. 1 5
  5. 2 4
  6. 3 5
  1. import java.util.*;
  2. class Solution{
  3. boolean[] f;
  4. public void solve(int[][] graph, int N, int b){
  5. f = new boolean[N + 1];
  6. Queue<Integer> q = new LinkedList<>();
  7. q.offer(b);
  8. f[b] = true;
  9. //res存储每一个节点
  10. ArrayList<Integer> res = new ArrayList<>();
  11. while(!q.isEmpty()){
  12. int cur = q.poll();
  13. // System.out.print(cur + " ");
  14. res.add(cur);
  15. for(int i = 0; i <= N; i++){
  16. if(graph[cur][i] == 1 && f[i] == false){
  17. q.offer(i);
  18. f[i] = true;
  19. }
  20. }
  21. }
  22. for(int x : res){
  23. System.out.print(x + " ");
  24. }
  25. }
  26. }
  27. public class Main {
  28. public static void main(String[] args) {
  29. Scanner cin = new Scanner(System.in);
  30. int N = cin.nextInt();
  31. int[][] graph = new int[N + 1][N + 1];
  32. int M = cin.nextInt();
  33. for(int i = 0; i <= N; i++){
  34. for(int j = 0; j <= N; j++){
  35. if(i == j) graph[i][j] = 0;
  36. else graph[i][j] = Integer.MAX_VALUE;
  37. }
  38. }
  39. for(int i = 0; i < M; i++){
  40. int a = cin.nextInt();
  41. int b = cin.nextInt();
  42. graph[a][b] = 1;
  43. graph[b][a] = 1;
  44. }
  45. new Solution().solve(graph, N, 1);
  46. }
  47. }