[백준]1260번 DFS와 BFS

Yeeun_Kim·2023년 11월 2일
0
post-thumbnail

문제풀이(JAVA)

import java.util.*;
import java.io.*;

/**
 * 첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다.
 * 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다.
 * 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
 */

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());
        int v = Integer.parseInt(st.nextToken());

        boolean[] visited = new boolean[n+1];
        boolean[][] graph = new boolean[n+1][n+1];

        for(int i = 0; i<m;i++) {
            st = new StringTokenizer(br.readLine());
            int node1 = Integer.parseInt(st.nextToken());
            int node2 = Integer.parseInt(st.nextToken());
            graph[node1][node2] = true;
            graph[node2][node1] = true;
        }

        dfs(visited, graph, v);
        System.out.println();
        visited = new boolean[n+1];
        bfs(visited, graph, v);
    }

    public static void dfs(boolean[] visited, boolean[][] graph, int node) {
        visited[node] = true;
        System.out.print(node+" ");
        for(int i = 1; i < visited.length; i++) {
            if(graph[node][i] == true && visited[i] == false) {
                dfs(visited, graph, i);
            }
        }
    }

    public static void bfs(boolean[] visited, boolean[][] graph, int node) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(node);
        visited[node] = true;

        while (!queue.isEmpty()) {
            int visitNode = queue.poll();
            System.out.print(visitNode+" ");
            for(int i = 1; i < visited.length; i++) {
                if(graph[visitNode][i] == true && visited[i] == false) {
                    queue.offer(i);
                    visited[i] = true;
                }
            }
        }
    }
}

0개의 댓글