728x90
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
// 코드
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
62
63
64
65
66
67
|
import java.util.*;
import java.io.*;
public class Main{
static int N;
static int[][] arr;
static boolean[] visited;
static int min = Integer.MAX_VALUE;
static int start = 1;
// 임의의 (1,1)도시를 하나씩 돌며 가중치를 더해가고 가중치 중 최소값을 찾는다.
static void dfs(int city, int cnt, int cost) {
// 기저조건 : 방문횟수가 N과 같을 때
if(cnt == N && start != city && cost > 0 && arr[city][start] > 0) {
// 탐방을 완료했을 경우
// 시작점은 이미 방문 처리가 되었으므로
// 마지막 도시에서 처음 시작도시로의 가중치 값은 구해지지 않았다.
// 별도로 구해준다.
cost += arr[city][start];
// 최종 구해진 거리 가중치 합산 값과 기존 합산값을 비교해 최소값을 넣어준다.
min = Math.min(min, cost);
return;
}
// 각 도시를 방문한다. 즉 다음 방문할 도시를 뜻한다.
for(int i=1; i<=N; i++) {
if(arr[city][i] == 0) continue; // 자기가 위치한 도시인 경우는 탐방불가
if(visited[i]) continue; // 이미방문한 도시면 탐방불가
visited[i] = true;
dfs(i, cnt+1, cost+arr[city][i]);
visited[i] = false;
}
}
// main
public static void main(String[] args) throws Exception {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = new int[N+1][N+1];
for(int i=1; i<=N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j=1; j<=N; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
visited = new boolean[N+1];
for(int i=1; i<=N; i++) {
visited[i] = true;
dfs(i, 1, 0);
}
bw.write(String.valueOf(min));
br.close();
bw.flush();
bw.close();
}
}
|
cs |
반응형
'CS > 알고리즘_문제풀이(자바)' 카테고리의 다른 글
엄청난 부자2 (0) | 2021.10.11 |
---|---|
로또 (0) | 2021.10.08 |
쉬운 계단 수 (0) | 2021.10.07 |
1, 2, 3 더하기 5 (0) | 2021.10.07 |
토마토 (0) | 2021.10.06 |