输入
5 5 #几个点 几条边1 2 #具体边的连接1 31 52 43 5
import java.util.*;class Solution{ boolean[] f; public void solve(int[][] graph, int N, int b){ f = new boolean[N + 1]; Queue<Integer> q = new LinkedList<>(); q.offer(b); f[b] = true; //res存储每一个节点 ArrayList<Integer> res = new ArrayList<>(); while(!q.isEmpty()){ int cur = q.poll(); // System.out.print(cur + " "); res.add(cur); for(int i = 0; i <= N; i++){ if(graph[cur][i] == 1 && f[i] == false){ q.offer(i); f[i] = true; } } } for(int x : res){ System.out.print(x + " "); } }}public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int N = cin.nextInt(); int[][] graph = new int[N + 1][N + 1]; int M = cin.nextInt(); for(int i = 0; i <= N; i++){ for(int j = 0; j <= N; j++){ if(i == j) graph[i][j] = 0; else graph[i][j] = Integer.MAX_VALUE; } } for(int i = 0; i < M; i++){ int a = cin.nextInt(); int b = cin.nextInt(); graph[a][b] = 1; graph[b][a] = 1; } new Solution().solve(graph, N, 1); }}