Iyoungman Back-end Developer

BOJ 1260. DFS와 BFS

2020-05-04

Problem

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


Think

  • 기본적인 DFS, BFS 문제이다.
  • DFS는 재귀함수 or Stack을 이용해서 구현했다.
  • BFS는 Queue를 이용해서 구현했다.


Solved Code

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class Main {

    private static int[][] graph;
    private static boolean[] isVisit;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] splits = br.readLine().split(" ");
        int n = Integer.parseInt(splits[0]);
        int m = Integer.parseInt(splits[1]);
        int v = Integer.parseInt(splits[2]);

        graph = new int[n + 1][n + 1];
        for (int i = 0; i < m; i++) {
            splits = br.readLine().split(" ");
            int v1 = Integer.parseInt(splits[0]);//연결 정점1
            int v2 = Integer.parseInt(splits[1]);//연결 정점2

            graph[v1][v2] = 1;
            graph[v2][v1] = 1;
        }

        isVisit = new boolean[n + 1];
        dfsByStack(v);//dfsByRecursive(v)

        System.out.println();

        isVisit = new boolean[n + 1];
        bfs(v);
    }

    private static void dfsByRecursive(int current) {
        isVisit[current] = true;
        System.out.print(current + " ");

        for (int i = 1; i < graph.length; i++) {
            if (graph[current][i] == 1 && !isVisit[i]) {
                dfsByRecursive(i);
            }
        }

    }

    private static void dfsByStack(int start) {
        Stack<Integer> stack = new Stack<>();
        stack.push(start);

        isVisit[start] = true;
        System.out.print(start + " ");

        while (!stack.isEmpty()) {
            int current = stack.peek();

            boolean isContainNext = false;
            for (int i = 1; i < graph.length; i++) {
                if (graph[current][i] == 1 && !isVisit[i]) {
                    stack.push(i);
                    isVisit[i] = true;
                    isContainNext = true;

                    System.out.print(i + " ");
                    break;
                }
            }

            if (!isContainNext) {
                stack.pop();
            }
        }

    }

     private static void bfs(int start) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(start);
        isVisit[start] = true;

        while (!queue.isEmpty()) {
            int current = queue.poll();
            System.out.print(current + " ");

            for (int i = 1; i < graph.length; i++) {
                if (graph[current][i] == 1 && !isVisit[i]) {
                    isVisit[i] = true;
                    queue.offer(i);
                }
            }
        }

    }

}


Comments

Content