취미처럼

[백준] 10971번 외판원 순회 2 본문

Algorithm/백준

[백준] 10971번 외판원 순회 2

sirius 2021. 3. 4. 17:25
https://www.acmicpc.net/problem/10971
 

10971번: 외판원 순회 2

첫째 줄에 도시의 수 N이 주어진다. (2 ≤ N ≤ 10) 다음 N개의 줄에는 비용 행렬이 주어진다. 각 행렬의 성분은 1,000,000 이하의 양의 정수이며, 갈 수 없는 경우는 0이 주어진다. W[i][j]는 도시 i에서 j

www.acmicpc.net

 

 

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

public class Main {

    public static int N;
    public static int[][] arr;
    public static boolean[] visit;
    public static int min = Integer.MAX_VALUE;


    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        arr = new int[N][N];
        visit = new boolean[N];

        for(int y = 0; y < N; y++) {
            st = new StringTokenizer(br.readLine());
            for(int x = 0; x < N; x++) {
            	arr[y][x] = Integer.parseInt(st.nextToken());
            }
        }

        for(int i = 0; i < N; i++) {
            visit[i] = true;
            dfs(i, i, 0, 0);
        }

        System.out.println(min);
    }  

    // start = x, now = y
    public static void dfs(int start, int now, int depth, int sum) {
        // 처음 노드는 main에서 방문했으므로 N - 1
        if(depth == N - 1) {
            // 마지막 노드에서 맨 처음 노드로 가는 비용 계산
            if(arr[now][start] != 0 ) {
                sum += arr[now][start];
                min = Math.min(min, sum);
        	}
        	return;
        }

        for(int i = 0; i < N ; i++ ) {
            if(!visit[i] && arr[now][i] != 0 ) {
                visit[i] = true;
                dfs(start, i, depth + 1, sum + arr[now][i]);
                visit[i] = false;
            }
        }
    }
}

'Algorithm > 백준' 카테고리의 다른 글

[백준] 11723번 집합  (0) 2021.03.04
[백준] 6603번 로또  (0) 2021.03.04
[백준] 10819번 차이를 최대로  (0) 2021.03.04
[백준] 10974번 모든 순열  (0) 2021.03.04
[백준] 10973번 이전 순열  (0) 2021.03.04
Comments