-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1260_DFS์ BFS.java
More file actions
72 lines (64 loc) ยท 2.02 KB
/
1260_DFS์ BFS.java
File metadata and controls
72 lines (64 loc) ยท 2.02 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.LinkedList;
import java.util.Queue;
public class test2 {
static int N, M, V; //์ ์ ์, ๊ฐ์ ์, ์์ ๋
ธ๋
static int[][] graph;
static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
V = Integer.parseInt(st.nextToken());
//๊ทธ๋ํ ์ด๊ธฐํ
graph = new int[N+1][N+1];
for(int i = 0; i<M; i++) {
int x, y;
st = new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
graph[x][y] = 1;
graph[y][x] = 1;
}
visited = new boolean[N+1];
dfs(V);
System.out.println();
visited = new boolean[N+1];
bfs(V);
}
//๊น์ด ์ฐ์ ํ์
static void dfs(int idx){
visited[idx] = true;
System.out.print(idx + " ");
if(idx == graph.length) {
return;
}
for(int i=1; i< graph.length; i++){
if(graph[idx][i] == 1 && !visited[i]){
dfs(i);
}
}
}
//๋๋น ์ฐ์ ํ์
static void bfs(int idx) {
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(idx);
visited[idx] = true;
System.out.print(idx + " ");
while(!queue.isEmpty()){
int s =queue.poll();
for(int i =1; i< graph.length;i++){
if(graph[s][i] == 1 && !visited[i]){
queue.add(i);
visited[i] = true;
System.out.print(i + " ");
}
}
}
}
}