-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBAEKJOON_1260
More file actions
82 lines (67 loc) · 2.18 KB
/
BAEKJOON_1260
File metadata and controls
82 lines (67 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.io.*;
import java.util.*;
public class Main {
public static List<Integer>[] list;
public static Stack<Integer> s;
public static int start;
public static boolean[] v;
static BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(System.out));
public static Queue<Integer> q = new LinkedList<>();
public static void main(String[] args) throws IOException {
StringTokenizer st =new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken()); //정점 개수 4
int E = Integer.parseInt(st.nextToken()); //간선의 수 5
start = Integer.parseInt(st.nextToken()); //시작 점
list = new ArrayList[N+1];
v =new boolean[N+1];
Arrays.fill(v,false);
for(int i=1; i<N+1; i++){
list[i] = new ArrayList<>();
}
for(int i=0; i<E; i++){
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
list[x].add(y);
list[y].add(x);
}
for(int i=1; i<N+1; i++){
list[i].sort(Comparator.naturalOrder());
}
dfs(start);
Arrays.fill(v,false);
bw.newLine();
bfs(start);
bw.flush();
bw.close();
}
public static void dfs(int start)throws IOException{
if(v[start]==true){
return;
}
v[start] = true;
bw.write(String.valueOf(start)+" ");
for(int i : list[start]){
int next = i;
if(v[next] == false){
dfs(next);
}
}
}
public static void bfs(int start)throws IOException{
v[start]=true;
q.add(start);
while(!q.isEmpty()){
int x = q.poll();
bw.write(String.valueOf(x)+" ");
for(int i : list[x]){
int next = i;
if(v[next]==false){
v[next]=true;
q.add(next);
}
}
}
}
}