Search

'Java'에 해당되는 글 6건

  1. 2019.12.17 백준 1260 - DFS와 BFS

백준 1260 - DFS와 BFS

it/알고리즘 2019. 12. 17. 22:58 Posted by 하얀나다
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
import java.util.Scanner;
 
public class Main {
 
    static int N,M,S;
    static int[][] map;
    static boolean[] visit;
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        
        N = sc.nextInt();
        M = sc.nextInt();
        S = sc.nextInt();
        map = new int[N+1][N+1];
        for(int i = 0 ; i<M ; i++){
            int x = sc.nextInt();
            int y = sc.nextInt();
            map[x][y] = 1;
            map[y][x] = 1;
        }
        visit = new boolean[N+1];
        DFS(S);
        System.out.println();
        visit = new boolean[N+1];
        BFS(S);
        
    }
    private static void BFS(int s) {
        Queue<Integer> q = new LinkedList<Integer>();
        q.add(s);
        visit[s] = true;        
        while(!q.isEmpty()){
            int n = q.remove();
            System.out.print(n + " ");
            for(int i = 0 ; i<map.length ; i++){
                if(map[n][i] == 1 && visit[i] == false){
                    visit[i] = true;
                    q.add(i);
                }
            }
        }
        
    }
    private static void DFS(int s) {
        System.out.print(s+" ");
        visit[s] = true;
        for(int i = 0 ; i<map.length ; i++){
            if(map[s][i] == 1 && visit[i] == false){
                DFS(i);
            }
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

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

백준 1735 - 분수 합  (0) 2019.12.17
백준 1516 - 게임 개발  (0) 2019.12.17
백준 1110 - 더하기 사이클  (0) 2019.12.17
백준 1058 - 친구  (0) 2019.12.17
백준 1012 - 유기농 배추  (0) 2019.12.17