luogu1219 [八皇后] 搜索

把每行選的數作爲狀態,按字典序的順序搜索。

#include <cmath>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 103 + 5 ;
int li [N] , zu [N] , yo [N] , a [N] ;
int n , ans;

void dfs ( int h ){
    for ( int i = 1 ; i <= n ; ++ i ) {
        if ( ( !li [i] ) && (! zu [ h-i+20 ] ) && (! yo [h+i] ) ){
            li [i] = zu [ h-i+20 ] = yo [h+i] = 1 ;
            a [h] = i ;
            if ( h == n ){
                ans ++ ;
                if ( ans <= 3 ){
                    for ( int j = 1 ; j <= n ; ++ j ) 
                        printf ( "%d " , a [j] ) ;
                    puts(""); 
                }
            }else {
                dfs ( h+1 ) ;
            }
            li [i] = zu [ h-i+20 ] = yo [h+i] = 0 ;
        }
    }
}
int main () {
    scanf ( "%d" , &n ) ;
    ans = 0 ;
    dfs (1);
    printf ( "%d" , ans ) ;
    return 0 ;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章