zoukankan      html  css  js  c++  java
  • 52. N-Queens II

    一、题目

      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;
        }
    }
  • 相关阅读:
    linux静态链接库
    查看进程运行时间
    进程间同步-互斥量
    Linux——多线程下解决生产消费者模型
    Linux——线程
    浅谈智能指针的历史包袱
    C++ 模板基础
    用信号量为共享内存添加同步机制
    Linux——浅析信号处理
    浅析fork()和底层实现
  • 原文地址:https://www.cnblogs.com/skillking/p/9650408.html
Copyright © 2011-2022 走看看