230404 N-Queen

Jongleee·2023년 4월 4일
0

TIL

목록 보기
224/576
private static final int MAX = 12;
private static int[] location = new int[MAX];
private static int cnt = 0;

public static int solution(int n) {
    dfs(0, n);
    return cnt;
}
private static boolean isPossible(int row) {
    for (int i = 0; i < row; i++) {
        if (location[row] == location[i]
                || Math.abs(row - i) == Math.abs(location[row] - location[i])) {
            return false;
        }
    }
    return true;
}

private static void dfs(int row, int n) {
    if (row == n) {
        cnt++;
        return;
    }

    for (int col = 0; col < n; col++) {
        location[row] = col;
        if (isPossible(row)) {
            dfs(row + 1,n);
        }
    }
}

dfs를 이용하고 1차원 배열만으로 조건을 판별함

출처:https://school.programmers.co.kr/learn/courses/30/lessons/12952

0개의 댓글