본문 바로가기
공부/알고리즘

백준1260_DFS와 BFS

by 미네밍 2017. 3. 9.

문제

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다.

입력

첫째 줄에 정점의 개수 N(1≤N≤1,000), 간선의 개수 M(1≤M≤10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 한 간선이 여러 번 주어질 수도 있는데, 간선이 하나만 있는 것으로 생각하면 된다. 입력으로 주어지는 간선은 양방향이다.

출력

첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

예제 입력 

4 5 1
1 2
1 3
1 4
2 4
3 4

예제 출력 

1 2 4 3
1 2 3 4


[코드]


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.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
public class Main {
    
    
    public static LinkedList<Integer>[] list;
    public static boolean visited[];
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int v = sc.nextInt(); //정점 개수
        int e = sc.nextInt(); //간선 개수
        int f = sc.nextInt(); //시작정
        
        list = new LinkedList[v+1];
        visited = new boolean[v+1]; 
        for(int i = 1 ; i <= v;i++)
            list[i] = new LinkedList();
        
        for(int i = 0 ; i < e; i++){
            int x = sc.nextInt();
            int y = sc.nextInt();
            list[x].addLast(y);
            list[y].addLast(x);
            Collections.sort(list[x]);
            Collections.sort(list[y]);
        }
        
        DFS(f);
        
        for(int i = 1 ; i <= v;i++)
            visited[i] = false;
        
        System.out.println();
        
        BFS(f);
        System.out.println();
    }
 
    public static void DFS(int f){
            visited[f] = true;
            System.out.print(f + " ");
            Iterator<Integer> it = list[f].iterator();
            while(it.hasNext()){
                int next = it.next();
                if(!visited[next]) DFS(next);
            }
    }
    
    public static void BFS(int f){
        Queue<Integer> q = new LinkedList<Integer>();
        q.add(f);
        while(!q.isEmpty()){
            int cur = q.poll();
            if(visited[cur])
                continue;
            visited[cur] = true;
            System.out.print(cur + " ");
            Iterator<Integer> it = list[cur].iterator();
            while(it.hasNext()){
                int next = it.next();
                    q.add(next);
            }
        }
    }
}
 
 
cs


[알고리즘]


인접리스트를 이용해 풀어보았다.


방문할 수 있는 정점이 여러개인 경우는 더 작은 정점을 기준으로 한다는 문제의 조건 때문에 LinkedList 의 노드들을 정렬시켜 줬다.


'공부 > 알고리즘' 카테고리의 다른 글

백준9328_열쇠  (0) 2017.04.11
백준1238_파티  (0) 2017.03.09
백준9095_1,2,3 더하기  (2) 2017.01.16
백준1152_단어의 개수  (0) 2017.01.11
백준1916_최소비용 구하기  (2) 2017.01.09

댓글