zoukankan      html  css  js  c++  java
  • Leetcode:52. N-QueensII

    Description

    Follow up for N-Queens problem.

    Now, instead outputting board configurations, return the total number of distinct solutions.

    思路

    • 递归方式
    • 主要是要判断当前位置是否是合理位置,参考isValid函数

    代码

    class Solution {
    public:
        int totalNQueens(int n) {
            int res = 0;
            if(n == 0) return 0;
            
            vector<string> flag(n, string(n, '.'));
            getResult(flag, n, 0, res);
            
            return res;
        }
        
        void getResult(vector<string> &flag, int n, int rows, int &res){
            if(rows == n){
                res++;
                return;
            }
            else{
                for(int i = 0; i < n; ++i){
                    if(isValid(flag, rows, i, n)){
                        flag[rows][i] = 'Q';
                        getResult(flag, n, rows + 1, res);
                        flag[rows][i] = '.';
                    }
                }
            }
        }
        bool isValid(vector<string> &nums, int rows, int cols, int n){
            for(int i = 0; i < rows; ++i)
                if(nums[i][cols] == 'Q') return false;
                
            for(int i = rows - 1, j = cols - 1; i >= 0 && j >= 0; --i, --j)
                if(nums[i][j] == 'Q') return false;
                
            for(int i = rows - 1, j = cols + 1; i >= 0 && j < n; --i, ++j)
                if(nums[i][j] == 'Q') return false;
                
            return true;
        }
    };
    
  • 相关阅读:
    spring mvc 总结
    linux安装tomcat及优化
    mysql支持emoji表情
    面试问题
    linux安装jdk mysql
    webstorm 介绍
    spring 总结
    UML工具
    js bom dom
    awt多线程聊天
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6855805.html
Copyright © 2011-2022 走看看