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
문제
풀이
DFS완전탐색 + 백트래킹 문제이다.
출발도시를 각자 주어진 도시마다 설정해놓고
dfs 재귀호출로 이동할 수 있는 다른 도시들을 완전 탐색을 진행하면서
만약 모든 도시를 다 탐색 했을 경우 , 방문했던 도시를 다시 방문하지 않은 것으로 백트래킹시켜준다.
모든 도시를 다 탐색했을 경우엔 이때까지 비용들의 총합과 현재 최소비용을 비교하면서 갱신하면 끝
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
import java.util.*;
import java.io.*;
public class Main{
static ArrayList<Node>[] path;
static int N,start,min;
static boolean[] visit;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//그래프 초기화
N = Integer.parseInt(br.readLine());
path = new ArrayList[N];
visit = new boolean[N];
for(int i=0;i<N;i++){
path[i] = new ArrayList<>();
int[] input = Arrays.stream(br.readLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
for(int e=0;e<input.length;e++){
if(input[e]==0) continue;
path[i].add(new Node(e,input[e]));
}
}
//탐색
int min=Integer.MAX_VALUE;
for(int i=0;i<N;i++,start=i) dfs(i,0,0);
System.out.println(min);
}
private static void dfs(int cur,int depth,int totalCost) {
visit[cur]=true;
if(depth==N && cur==start){
min = Math.min(min,totalCost);
return;
}
for (Node next : path[cur]) {
if(next.node==start&&depth==N-1)
dfs(next.node,depth+1,totalCost+next.cost);
else if(visit[next.node]) continue;
dfs(next.node,depth+1,totalCost+next.cost);
}
visit[cur]=false;
}
static class Node{
int node;
int cost;
public Node(int node, int cost) {
this.node = node;
this.cost = cost;
}
}
}
|
cs |
'알고리즘,PS > 백준' 카테고리의 다른 글
[BOJ] 백준 [1041] 주사위 JAVA (0) | 2021.10.24 |
---|---|
[BOJ] 백준 [16236] 아기 상어 JAVA (0) | 2021.10.22 |
[BOJ] 백준 [2146] 다리만들기 JAVA (0) | 2021.10.14 |
[BOJ] 백준 [9465] 스티커 JAVA (0) | 2021.10.13 |
[BOJ] 백준 [11054] 가장 긴 바이토닉 부분 수열 JAVA (0) | 2021.10.13 |