1. 程式人生 > >52. N-Queens II

52. N-Queens II

val inf style 問題 ali spa info urn color

一、題目

  1、審題

  技術分享圖片

  2、分析:

    輸入數字n, 求 n-皇後問題存在幾個解。

二、解答

  1、思路:

    同上一題,只是采用一個參數對解的個數進行記錄,最終 DFS 返回的即為所求解個數。

class Solution {
    public int totalNQueens(int n) {
        char[][] arr = new char[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                arr[i][j] 
= ‘.‘; } } int total = helper(arr, n, 0, 0); return total; } private int helper(char[][] arr, int n, int row, int total) { if(row == n) { return ++total; } else { for (int column = 0; column < n; column++) {
if(isValid2(arr, row, column, n)) { arr[row][column] = ‘Q‘; total = helper(arr, n, row+1, total); arr[row][column] = ‘.‘; } } } return total; } private boolean isValid2(char[][] arr, int
row, int column, int n) { // check the column for (int i = 0; i < row; i++) if(arr[i][column] == ‘Q‘) return false; // check the 45 o for (int i = row -1, j = column - 1; i >= 0 && j >= 0; i--, j--) if(arr[i][j] == ‘Q‘) return false; // check the 135 o for(int i = row -1, j = column + 1; i >= 0 && j < n; --i, ++j) if(arr[i][j]== ‘Q‘ ) return false; return true; } }

52. N-Queens II