import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static Queue<Integer> q = new LinkedList<>();
static int N,M,V,x,y;
static int[][] arr;
static int[] visit;
public static void DFS(int v){
System.out.print(v + " ");
visit[v]=1;
for(int i=1;i<=N;i++){
if(visit[i]==0 && arr[v][i]==1){
DFS(i);
}
}
}
public static void BFS(int v){
q.add(v);
visit[v]=0;
while(!q.isEmpty()){
v = q.peek();
System.out.print(v+" ");
q.poll();
for(int i=1;i<=N;i++){
if(visit[i]==1 && arr[v][i]==1){
q.add(i);
visit[i]=0;
}
}
}
}
public static void main(String args[])throws IOException{
st = new StringTokenizer(br.readLine()," ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
V = Integer.parseInt(st.nextToken());
arr = new int[N+1][N+1];
visit = new int[N+1];
for(int i=0;i<M;i++){
st = new StringTokenizer(br.readLine()," ");
x=Integer.parseInt(st.nextToken());
y=Integer.parseInt(st.nextToken());
arr[x][y] = 1;
arr[y][x] = 1;
}
DFS(V);
System.out.println();
BFS(V);
}
}
그리디를 풀다가 BFS관한 문제가나왔는데 도저히 길이 안보여서 탐색알고리즘을 좀 공부하려고 한다.
DFS는 의외로 쉬운데 BFS가 조금 어려운것 같다...ㅠ