https://www.acmicpc.net/problem/1260
import java.util.*;
public class Main {
static int[][] edge;
static boolean[] check;
static int n;
static int m;
static int v;
static void dfs(int v){
check[v]=true;
System.out.print(v+" ");
for(int i=1;i<=n;i++){
if(edge[v][i]==1 && check[i]==false) dfs(i);
}
}
static void bfs(int s){
Queue<Integer> q=new LinkedList();
q.add(s);
check[s]=true;
while(q.isEmpty()==false){
int v=q.peek();
q.poll();
System.out.print(v+" ");
for(int i=1;i<=n;i++){
if(edge[v][i]==1 && check[i]==false){
q.add(i);
check[i]=true;
}
}
}
}
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
n=s.nextInt();
m=s.nextInt();
v=s.nextInt();
edge=new int[n+1][n+1];
check=new boolean[n+1];
while(m-->0){
int f=s.nextInt();
int t=s.nextInt();
edge[f][t]=edge[t][f]=1;
}
dfs(v);
check=new boolean[n+1];
System.out.println();
bfs(v);
}
}