Algorithm/백준

[백준] Silver I. 스타트와 링크

미네구스 2024. 9. 26. 14:08

https://www.acmicpc.net/problem/14889

 

문제 유형
  • 브루트 포스 
  • 백트래킹

 

풀이
public class boj14889 {
    static int n;
    static int [][] board;
    static boolean [] visited;
    static int res = Integer.MAX_VALUE;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());

        board = new int[n][n];
        visited = new boolean[n];
        for(int i = 0; i < n; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            for(int j = 0; j < n; j++) {
                board[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        dfs(0, 0);
        System.out.println(res);
    }

    public static void dfs(int idx, int cnt) {
        if (cnt == n/2) {
            int start = 0;
            int link = 0;

            for(int i = 0; i < n - 1; i++) {
                for(int j = i + 1; j < n; j++) {
                    if (visited[i] && visited[j]) {
                        start += board[i][j] + board[j][i];
                    }

                    if (!visited[i] && !visited[j]) {
                        link += board[i][j] + board[j][i];
                    }
                }
            }
            res = Math.min(res, Math.abs(link - start));
            return;
        }

        for(int i = idx; i < n; i++) {
            if (!visited[i]) {
                visited[i] = true;
                dfs(i, cnt + 1);
                visited[i] = false;
            }
        }
    }
}

 

 

회고