

์ฃผ์ด์ง ๊ทธ๋ํ๋ฅผ DFS ์ BFS๋ฅผ ํตํด ํ์์ ํ ์์์ ๋ํด ์ถ๋ ฅํ๋ค.
์ ๋ ฅ๋ฐ์ ๊ทธ๋ํ์ ๋ฐฉ๋ฌธ ์ฌ๋ถ ๋ฐฐ์ด์ static ๋ณ์๋ก ์ ์ธํ์ฌ ์ฌ์ฉํ๋ค.
private static void dfs(int start) {
check[start] = true;
sb.append(start + " ");
for (int i = 0; i <= node; i++) {
if (arr[start][i] == 1 && !check[i]) {
dfs(i);
}
}
}
private static void bfs(int start) {
q.add(start);
check[start] = true;
while(!q.isEmpty()) {
start = q.poll();
sb.append(start + " ");
for (int i = 0; i <=node; i++) {
if (arr[start][i] == 1 && !check[i]) {
q.add(i);
check[i] = true;
}
}
}
}
public class Main {
static StringBuilder sb = new StringBuilder();
static boolean[] check;
static int[][] arr;
static int node, line, start;
static Queue<Integer> q = new LinkedList<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
node = Integer.parseInt(st.nextToken());
line = Integer.parseInt(st.nextToken());
start = Integer.parseInt(st.nextToken());
arr = new int[node+1][node+1];
check = new boolean[node+1];
// ๊ฐ์ ๋
ธ๋ ๊ทธ๋ํ ์
๋ ฅ
for (int i = 0; i < line; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
arr[a][b] = arr[b][a] = 1;
}
dfs(start);
sb.append("\n");
check = new boolean[node+1];
bfs(start);
System.out.println(sb);
}
// DFS ์ ์
private static void dfs(int start) {
check[start] = true;
sb.append(start + " ");
for (int i = 0; i <= node; i++) {
if (arr[start][i] == 1 && !check[i]) {
dfs(i);
}
}
}
// BFS ์ ์
private static void bfs(int start) {
q.add(start);
check[start] = true;
while(!q.isEmpty()) {
start = q.poll();
sb.append(start + " ");
for (int i = 0; i <=node; i++) {
if (arr[start][i] == 1 && !check[i]) {
q.add(i);
check[i] = true;
}
}
}
}
}
๋ฐ๋ผ์ O(N^2) ์ ์๊ฐ๋ณต์ก๋๋ฅผ ๊ฐ๋๋ค.