zoukankan      html  css  js  c++  java
  • [LeetCode] N-Queens II

    Follow up for N-Queens problem.

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

    思路:与http://www.cnblogs.com/vincently/p/4714230.html思路相同。

    class Solution {
    public:
        int result;
        int queen_num_;
        int totalNQueens(int n) {
            result = 0;
            vector<int> a(n, -1);
            queen_num_ = n;
            solveNQueens(a);
            
            return result;
        }
        
        bool IsValid(const vector<int>& a, int row, int col) {
            for (int i = 0; i < row; i++) {
                if (col == a[i] || abs(i - row) == abs(a[i] - col))
                    return false;
            }
    
            return true;
        }
    
        void solveNQueens(vector<int>& a) {
            int i = 0, j = 0;
            while (i < queen_num_) {
                while (j < queen_num_) {
                    if (IsValid(a, i, j)) {
                        a[i] = j;
                        j = 0;
                        break;
                    } else {
                        j++;
                    }
                }
    
                if (a[i] == -1) {
                    if (i == 0) {
                        return;
                    } else {
                        i--;
                        j = a[i] + 1;
                        a[i] = -1;
                        continue;
                    }
                }
    
                if (i == queen_num_  - 1) {
                    result++; 
                    j = a[i] + 1;
                    a[i] = -1;
                    continue;
                }
             i++;
            }//while (i < queen_num_);
        }//solveNQueens
    };
  • 相关阅读:
    Git简介
    git 目录
    版本控制系统介绍
    python 爬虫 基于requests模块发起ajax的post请求
    python 爬虫 基于requests模块发起ajax的get请求
    POJ 2575
    POJ 2578
    POJ 2562
    POJ 2572
    POJ 2560
  • 原文地址:https://www.cnblogs.com/vincently/p/4714635.html
Copyright © 2011-2022 走看看