๐Ÿ—๏ธ Algorithm/๐ŸŸฉ ๋ฐฑ์ค€

๐ŸŸฉ [๋ฐฑ์ค€] [Java] [Silver2] 1260๋ฒˆ_DFS์™€ BFS

Dbswnstjd 2024. 1. 8. 00:01

๋ฌธ์ œ

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

 

1260๋ฒˆ: DFS์™€ BFS

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ

www.acmicpc.net

ํ’€์ด

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    static int[][] arr;
    static boolean[] visited;

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int N = scan.nextInt();   // ์ •์ ์˜ ๊ฐœ์ˆ˜
        int M = scan.nextInt();   // ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜
        int V = scan.nextInt();   // ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์  ๋ฒˆํ˜ธ

        //์ธ์ ‘ํ–‰๋ ฌ ์ƒ์„ฑ
        arr = new int[N+1][N+1];
        for(int i = 0; i < M; i++) {
            int a = scan.nextInt();
            int b = scan.nextInt();
            arr[a][b] = 1;
            arr[b][a] = 1;
        }

        visited = new boolean[N + 1];
        dfs(V);

        System.out.println();

        visited = new boolean[N + 1];
        bfs(V);
    }
    //๊นŠ์ด์šฐ์„ ํƒ์ƒ‰(์žฌ๊ท€)
    public static void dfs(int V) {
        visited[V] = true;
        System.out.print(V + " ");

        if(V == arr.length) {
            return;
        }
        for(int j = 1; j < arr.length; j++) {
            //์—ฐ๊ฒฐ์€ ๋˜์–ด์žˆ๋Š”๋ฐ, ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ์žฌ๊ท€
            if(arr[V][j] == 1 && visited[j] == false) {
                dfs(j);
            }
        }
    }

    //๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰(ํ)
    public static void bfs(int V) {
        Queue<Integer> que = new LinkedList<Integer>();

        que.add(V);
        visited[V] = true;
        System.out.print(V + " ");

        while(!que.isEmpty()) {
            int temp = que.poll();
            for(int i = 1; i < arr.length; i++) {
                if(arr[temp][i] == 1 && visited[i] == false) {
                    que.add(i);
                    visited[i] = true;
                    System.out.print(i + " ");
                }
            }
        }
    }
}