๊ธฐ๋ก๋ฐฉ

BOJ_10971 : ์™ธํŒ์› ์ˆœํšŒ 2 ๋ณธ๋ฌธ

CodingTest/Java

BOJ_10971 : ์™ธํŒ์› ์ˆœํšŒ 2

Soom_1n 2023. 4. 6. 14:56

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

10971๋ฒˆ: ์™ธํŒ์› ์ˆœํšŒ 2

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. (2 ≤ N ≤ 10) ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๋น„์šฉ ํ–‰๋ ฌ์ด ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ–‰๋ ฌ์˜ ์„ฑ๋ถ„์€ 1,000,000 ์ดํ•˜์˜ ์–‘์˜ ์ •์ˆ˜์ด๋ฉฐ, ๊ฐˆ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ๋Š” 0์ด ์ฃผ์–ด์ง„๋‹ค. W[i][j]๋Š” ๋„์‹œ i์—์„œ j

www.acmicpc.net



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • N๊ฐœ์˜ ๋„์‹œ์—์„œ ๋ชจ๋“  ๋„์‹œ๋ฅผ ๋ฐฉ๋ฌธํ•˜๊ณ  ๋งˆ์ง€๋ง‰์— ์ถœ๋ฐœ์ง€๋กœ ๋Œ์•„์˜ค๋Š” ์—ฌํ–‰ ๊ฒฝ๋กœ ์ค‘ ๊ฐ€์žฅ ์ ์€ ๋น„์šฉ์„ ์ถœ๋ ฅํ•œ๋‹ค.
  • ์žฌ๊ท€์™€ ๋ฐฑํŠธ๋ž˜ํ‚น์„ ํ†ตํ•ด ๊ตฌํ˜„ํ•œ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    private static int N, W[][], MIN, ans, city;
    private static boolean[] visited;

    private static void recursion(int now, int cost, int cnt) {
        if (cost > MIN) {
            return;
        }
        if (cnt == N) {
            if (W[now][city] > 0) {
                cost += W[now][city];
                MIN = Math.min(MIN, cost);
            }
            return;
        }
        for (int i = 0; i < N; i++) {
            if (!visited[i] && W[now][i] > 0) {
                visited[i] = true;
                recursion(i, cost + W[now][i], cnt + 1);
                visited[i] = false;
            }
        }
    }

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

        N = Integer.parseInt(br.readLine());
        W = new int[N][N];

        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++) {
                W[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        // Recursion
        ans = Integer.MAX_VALUE;
        for (int i = 0; i < N; i++) {
            city = i;
            MIN = Integer.MAX_VALUE;
            visited = new boolean[N];
            visited[i] = true;
            recursion(i, 0, 1);
            ans = Math.min(ans, MIN);
        }

        // Output
        System.out.println(ans);
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • ๋ชจ๋“  ๋„์‹œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ์ถœ๋ฐœ์ง€(๋„์ฐฉ์ง€)๋กœ ๋‘๊ณ , ์žฌ๊ท€ ๋ฉ”์„œ๋“œ recursion()์„ ํ˜ธ์ถœํ•œ๋‹ค.
    • recursion() ์•ˆ์—์„œ ํ•˜๋‚˜์”ฉ ๋ฐฉ๋ฌธํ•ด ๋ณธ๋‹ค.
    • ๋ชจ๋“  ๋„์‹œ๋ฅผ ๋ฐฉ๋ฌธํ–ˆ์œผ๋ฉด ๋น„์šฉ์„ ๊ณ„์‚ฐํ•ด ์ตœ์†Œ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.
  • ๋น„์šฉ์„ ๋ˆ„์ ํ•ด์„œ ์žฌ๊ท€ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ, ์ „์ฒด ๋น„์šฉ ๊ณ„์‚ฐ์˜ ์ค‘๋ณต์„ ์ค„์ธ๋‹ค.
    • ์ด๋ฏธ ์ฐพ์€ ๋น„์šฉ๋ณด๋‹ค ํ˜„์žฌ ๋ˆ„์  ๋น„์šฉ์ด ์ปค์กŒ์œผ๋ฉด, ๋ณผ ํ•„์š”๋„ ์—†์œผ๋ฏ€๋กœ ๋ฆฌํ„ดํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์žฌ๊ท€๋ฅผ ๊ตฌํ˜„ํ•˜๋Š”๊ฑด ๊ฐ„๋‹จํ•˜์ง€๋งŒ, ๊ฐ ๋น„์šฉ์ด ์ตœ๋Œ€ 100๋งŒ๊นŒ์ง€ ๊ฐ€๋ฏ€๋กœ ๋ฐฑํŠธ๋ž˜ํ‚น์ด ๊ผญ ํ•„์š”ํ–ˆ๋‹ค.

728x90