-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathboj_1260.java
More file actions
74 lines (56 loc) · 1.92 KB
/
boj_1260.java
File metadata and controls
74 lines (56 loc) · 1.92 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
package dfs_bfs;
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 boj_1260 {
static StringBuilder sb = new StringBuilder();
static boolean[] chk;
static int[][] arr;
static int node, edge, 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());
edge=Integer.parseInt(st.nextToken());
start=Integer.parseInt(st.nextToken());
arr=new int[node+1][node+1]; //인접 행렬 사용 : 숫자가 낮은 노드부터 탐색해야하므로
chk=new boolean[node+1];
for(int i=0;i<edge;i++){ //edge만큼 반복해서 입력 받음
StringTokenizer st2= new StringTokenizer(br.readLine());
int a=Integer.parseInt(st2.nextToken());
int b=Integer.parseInt(st2.nextToken());
arr[a][b]=arr[b][a]=1;
}
dfs(start);
sb.append("\n");
chk=new boolean[node+1];
bfs(start);
System.out.println(sb);
}
public static void dfs(int start){ //재귀 사용
chk[start]=true;
sb.append(start+" ");
for(int i=0;i<=node;i++){
if (arr[start][i]==1 && !chk[i])
dfs(i);
}
}
public static void bfs(int start){//큐 사용
q.add(start);
chk[start]=true;
while(!q.isEmpty()){
start=q.poll();
sb.append(start+" ");
for(int i=1;i<=node;i++){
if(arr[start][i]==1 && !chk[i]){
q.add(i);
chk[i]=true;
}
}
}
}
}