• 52. N-Queens II (Array; Back-Track)


    Follow up for N-Queens problem.

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

    class Solution {
    public:
        int totalNQueens(int n) {
            result = 0;
            if(n==0) return result;
            
            vector<int> flag(n,-1); //每行的Q出现在哪列
            backTracking(n, flag, 0);
            return result;
    
        }   
        
        void backTracking(int n, vector<int>& flag, int depth){ //depth is the line number
            if(depth==n){
                result++;
                return;
            }
            
            for(int i = 0; i < n; i++){ //traverse column
                if(check(n,flag, depth, i)) {
                    flag[depth] = i;
                    backTracking(n,flag,depth+1);
                    flag[depth] = -1; // back track
                }
            }
        }
        
        bool check(int n, vector<int>& flag, int i, int j){
            for(int k = 0; k < i; k++){
                if(flag[k] < 0) continue;//no Q in this column
                if(flag[k]==j) return false;//check columns
                if(abs(i-k)==abs(j-flag[k])) return false; //check cross lines
            }
            return true;
        }
    private: 
        int result;
    };
  • 相关阅读:
    Redis常见7种使用场景(PHP)
    阻塞式I/O实现简单TCP通信
    telnet客户端程序
    TCP简单回射程序
    getsockname和getpeername函数
    close函数
    TCP时间获取程序
    listen函数
    基本套接字编程
    readline.c
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4856959.html
Copyright © 2020-2023  润新知