DFS์ BFS์ ๋ํ ๊ธฐ๋ณธ์ ์ธ ๊ฐ๋ ์ ๋์ง์ด๋ณผ ์ ์๋ ๋ฌธ์ ๋ผ ์๊ณ ๋ฆฌ์ฆ ๊ณต๋ถ ์์ํ ๋๋ง๋ค ๋ค์ ํ์ด๋ณด๊ฒ ๋๋ค.
์ด๋ฒ์ ํผ ์ฝ๋๋ ์๋์ ๊ฐ๋ค.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
public class Main1260_DFS์BFS {
static int N;
static int M;
static int start;
static Node[] graph;
static boolean[] visited;
static StringBuilder sb;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().trim().split(" ");
N = Integer.parseInt(str[0]);
M = Integer.parseInt(str[1]);
start = Integer.parseInt(str[2]);
graph = new Node[N+1];
visited = new boolean[N+1];
sb = new StringBuilder();
for(int n=1;n<=N;n++) {
graph[n] = new Node(n, new ArrayList<Integer>());
}
int first=0, second=0;
for(int m=1;m<=M;m++) {
str = br.readLine().trim().split(" ");
first = Integer.parseInt(str[0]);
second = Integer.parseInt(str[1]);
graph[first].link.add(second);
graph[second].link.add(first);
}
for(int i=1;i<=N;i++) {
Collections.sort(graph[i].link);
}
dfs(start);
sb.toString().trim();
sb.append("\n");
visited = new boolean[N+1];
bfs();
System.out.println(sb.toString());
}
private static void bfs() {
visited[start] = true;
sb.append(start+" ");
Queue<Integer> que = new LinkedList<Integer>();
que.offer(start);
int tmp;
ArrayList<Integer> list;
while(!que.isEmpty()) {
tmp = que.poll();
list = graph[tmp].link;
for (Integer i : list) {
if(!visited[i]) {
visited[i] = true;
sb.append(i+" ");
que.offer(i);
}
}
}
}
//์ผ๋จ ๋ฐฉ๋ฌธํ๊ธฐ๋ง ํ๋ฉด ๋.
//๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ์ฐพ์ ํ์๊ฐ ์์ผ๋ฏ๋ก visited[start]์ ์๋ณต์์ผ๋์ง ์๋๋ค.
private static void dfs(int start) {
visited[start] = true;
sb.append(start+" ");
ArrayList<Integer> list = graph[start].link;
for (Integer i : list) {
if(!visited[i]) {
dfs(i);
}
}
}
static class Node{
int nodeNum;
ArrayList<Integer> link;
public Node() {
}
public Node(int nodeNum, ArrayList<Integer> link) {
this.nodeNum = nodeNum;
this.link = link;
}
}
}
๊ตณ์ด Node Class๋ฅผ ๋ง๋ค ํ์๋ ์์๋๋ฐ ArrayList์ ๋ฐฐ์ด์ ์ด๋ป๊ฒ ๋ง๋ค์ด์ผ ํ ์ง ๋ชจ๋ฅด๊ฒ ์ด์ Node Class๋ฅผ ๋ง๋ค์๋ค.
๊ทผ๋ฐ ์ด์ ์ ํผ ์ฝ๋๋ฅผ ๋ณด๋๊น ArrayList์ ๋ฐฐ์ด์ ๋ง๋ค์ด๋จ๋๋ฐ, ์ง๊ธ๋ด๋ ์ดํด๊ฐ ์ ์ ๊ฐ๋๊ฑฐ ๋ณด๋๊น ๊ทธ๋ฅ ์ธ์์ ๋ง๋ค์๋๋ณด๋ค.
ArrayList<Integer>[] adList = adList = (ArrayList<Integer>[]) new ArrayList[N+1];
'์๊ณ ๋ฆฌ์ฆ > ๋ฌธ์ ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๋ฐ] ๋ฐฑ์ค 2667 - ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (0) | 2020.12.06 |
---|---|
[์๋ฐ] ๋ฐฑ์ค 2606 - ๋ฐ์ด๋ฌ์ค (0) | 2020.12.05 |
[์๋ฐ] ๋ฐฑ์ค 9372 - ์๊ทผ์ด์ ์ฌํ (0) | 2020.12.04 |
[์๋ฐ] ๋ฐฑ์ค 1068 - ํธ๋ฆฌ (0) | 2020.12.04 |
[์๋ฐ] ๋ฐฑ์ค 1167 - ํธ๋ฆฌ์ ์ง๋ฆ (0) | 2020.12.03 |