Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

작은 지식주머니

백준 자바 10971 외판원 순회2 본문

기타

백준 자바 10971 외판원 순회2

작지 2021. 10. 14. 20:57

링크: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

참조:https://lotuslee.tistory.com/92

 

 

 

package java10000;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class bj10971_외판원_순회2 {

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

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        N = Integer.parseInt(br.readLine());

        arr = new int[N + 1][N + 1];
        visited = new boolean[N + 1];

        for (int i = 1; i < N + 1; i++) {
            String[] s = br.readLine().split(" ");

            for (int j = 1; j < N + 1; j++) {
                arr[i][j] = Integer.parseInt(s[j - 1]);
            }
        }

        visited[1] = true;

        dfs(1, 1, 1, 0);
        bw.write(min + "\n");
        bw.flush();
        bw.close();
        br.close();
    }
    
    public static void dfs(int start, int cur, int cnt, int cost) {
        if (cur == start && cost > 0) {
            min = Math.min(min, cost);
            return;
        }
        for (int i = 1; i < N + 1; i++) {
            
            if (arr[cur][i] != 0) {
                if (i == start && cnt == N) {
                    cost += arr[cur][i];
                    dfs(start, i, cnt + 1, cost);
                }
                else if(!visited[i]){
                    visited[i] = true;
                    cost += arr[cur][i];
    
                    dfs(start, i, cnt + 1, cost);
                    
                    cost -= arr[cur][i];
                    visited[i] = false;
                }
            }
            
        }
    }
}

DFS 브루트포스로 해결함.

 

순환이 될 수 있고 열이 겹치지 않도록 계속 백 트래킹으로 계산하게 하였습니다.

if (cur == start && cost > 0) {
            min = Math.min(min, cost);
            return;
        }

RETURN값은 다시 1로 돌아왔을때 최소값을 도출하게 하였습니다.

if (i == start && cnt == N) {
                    cost += arr[cur][i];
                    dfs(start, i, cnt + 1, cost);
                }

DFS식 계산 전 VISITED[1]을 TRUE로 설정해놨기 떄문에 마지막 도착시의 계산을 따로 적어놨습니다.

 

 

'기타' 카테고리의 다른 글

프로그래머스 파이썬 타겟 넘버  (0) 2021.10.23
완전탐색 이분탐색  (0) 2021.10.17
프로그래머스 파이썬 소수 찾기  (0) 2021.10.13
프로그래머스 모의고사 파이썬  (0) 2021.10.11
자바 백준 2178 미로탐색  (0) 2021.10.07
Comments