10971. 외판원 순회2
10971번: 외판원 순회 2
첫째 줄에 도시의 수 N이 주어진다. (2 ≤ N ≤ 10) 다음 N개의 줄에는 비용 행렬이 주어진다. 각 행렬의 성분은 1,000,000 이하의 양의 정수이며, 갈 수 없는 경우는 0이 주어진다. W[i][j]는 도시 i에서 j
www.acmicpc.net
import java.util.Scanner;
public class JUN10971_ParkSomin {
static int[][] cost;
static boolean[] visited;
static int answer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
cost = new int[n][n];
visited = new boolean[n];
answer = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cost[i][j] = sc.nextInt();
}
}
for (int i = 0; i < n; i++) {
visited[i] = true;
dfs(i, i, 0, 1);
visited[i] = false;
}
System.out.println(answer);
}
static void dfs(int start, int now, int value, int cnt) {
int n = cost.length;
if (cnt == n) {
if (cost[now][start] != 0) {
value += cost[now][start];
answer = Math.min(answer, value);
}
return;
}
if (value > answer) {
return;
}
for (int j = 0; j < n; j++) {
if (now == j || visited[j] || cost[now][j] == 0) {
continue;
}
visited[j] = true;
dfs(start, j, value + cost[now][j], cnt + 1);
visited[j] = false;
}
}
}'코딩테스트 > JAVA 코테' 카테고리의 다른 글
| [JAVA][SWEA][BFS] 4193. 수영대회 결승전 (0) | 2023.04.07 |
|---|---|
| [JAVA] [DP] [DFS] 17070. 파이프 옮기기 1 (0) | 2023.03.29 |
| [JAVA][최단경로][다익스트라] 1238. 파티 (0) | 2023.03.19 |
| [JAVA] [백준] [BFS] 16236. 아기상어 (0) | 2023.03.07 |
| [SW] [D3] [DFS][조합] 9229. 한빈이와 Spot Mart (0) | 2023.03.05 |