52 N-Queens II

哈哈和51是一毛一样的backtracking,唯一区别就是比起每次找到最后生成一个板子,就是记个数,非常不要脸的发两篇


int cnt = 0;

public int totalNQueens(int n) {
    int[] queuePos = new int[n];
    queue(queuePos, 0);
    return cnt;
}

private boolean canPlace(int[] queuePos, int row, int col) {
    for(int i = 0; i < row; i++) {
        if(queuePos[i] == col) {
            return false;
        }
        if(Math.abs(i - row) == Math.abs(queuePos[i] - col)) {
            return false;
        }
    }
    return true;
}

private void queue(int[] queuePos, int row) {
    int n = queuePos.length;
    if(row == n) {
        cnt++;
        return;
    }
    for(int i = 0; i < n; i++) {
        if(canPlace(queuePos, row, i)) {
            queuePos[row] = i;
            queue(queuePos, row + 1);
        }
    }
}

results matching ""

    No results matching ""