티스토리 뷰

PS/boj

boj)1260 - DFS와 BFS

kingsubin 2020. 9. 3. 12:25
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int n, m, v;
    static LinkedList<Integer>[] nodeList;
    static boolean[] checked = new boolean[1001];
    static boolean[] checked2 = new boolean[1001];

    public static void dfs(int node) {
        if (checked[node]) return;

        checked[node] = true;
        System.out.print(node + " ");

        for (int nextNode : nodeList[node]) {
            dfs(nextNode);
        }
    }

    public static void bfs(int node) {
        Queue<Integer> q = new LinkedList<>();
        q.offer(node);

        while (!q.isEmpty()) {
            node = q.poll();

            if (checked2[node]) continue;

            checked2[node] = true;
            System.out.print(node + " ");

            for (int nextNode : nodeList[node]) {
                q.offer(nextNode);
            }
        }
    }

    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());

        nodeList = new LinkedList[n+1];
        // 그래프 초기화
        for (int i = 0; i <= n; i++) {
            nodeList[i] = new LinkedList<Integer>();
        }

        // 그래프에 숫자 넣기
        for (int i = 0; i < m; i++) {
            st = new StringTokenizer(br.readLine());

            int node1 = Integer.parseInt(st.nextToken());
            int node2 = Integer.parseInt(st.nextToken());

            nodeList[node1].add(node2);
            nodeList[node2].add(node1);

            Collections.sort(nodeList[node1]);
            Collections.sort(nodeList[node2]);
        }

        dfs(v);
        System.out.println();
        bfs(v);
    }

}

 

- 아직도 헷갈린다 ... 이해가 안되면 일단 외우기라도 해보자 , 계속 반복

 

 

1. dfs/bfs를 쓰기 위해서는 방문 체크가 필요함 boolean[] 선언 -> size 는 n의 max값 +1로 설정해서 static 사용

2. 입력정보를 담을 그릇을 LinkedList[] 사용, static 

3. LinkedList[] 초기화, nodeList[i] = new LinkedList();

4. nodeList[node1].add(node2), nodeList[node2].add[node1] 이런식으로 양쪽에 연결 정보를 입력

5. 들어오는 숫자가 정렬되어 있지 않으니까 Collections.sort로 nodeList를 오름차순 정렬 

 

6. dfs/ bfs 구현

7. dfs -> 재귀함수 이용 

7-1) 방문여부 체크

7-2) 방문 true, 출력

7-3) 해당 노드와 연결된 노드에 대해 반복문으로 다시 dfs 호출

8. bfs -> 큐 자료구조 이용

8-1) 큐에 넣기

8-2) while루프에서 큐 자료구조가 빌때까지 반복

8-3) 꺼내고 poll, 방문여부 체크

8-4) 방문 true, 출력 

8-5) 해당 노드와 연결된 노드들 큐에 넣기 offer 

 

 


https://www.acmicpc.net/problem/1260

'PS > boj' 카테고리의 다른 글

boj)2667 - 단지번호붙이기  (0) 2020.09.03
boj)2606 - 바이러스  (0) 2020.09.03
boj)18352 - 특정 거리의 도시 찾기  (0) 2020.09.02
boj)1459 - 걷기  (0) 2020.08.31
boj)12018 - Yonsei TOTO  (0) 2020.08.31