八皇后

回溯法, 全排列生成问题, 枚举量不超过 n! 个.

#define S 4
int n = S;
int tot = 0;
int C[S] = {0};
void m_search(int cur) {
    if ( cur == n ) {
        tot += 1;
        for ( int i = 0; i < n; i++ ) printf("%d ", C[i]); printf("\n");
        return;
    }
    for ( int i = 0; i < n; i++ ) {
        int ok = 1;
        C[cur] = i;
        for ( int j = 0; j < cur; j++ ) {
            if (( C[cur] == C[j] ) ||
               ( C[cur] == C[j] + (cur - j)) ||
               ( C[cur] == C[j] - (cur - j))) { 
                   ok = 0;
                break;
            }
        }
        if ( ok ) m_search(cur+1);
    }
}

int main() {
    m_search(0);
    printf("total: %d\n", tot);
    return 0;
}

 

posted @ 2012-12-07 12:28  tsubasa_wp  阅读(172)  评论(0编辑  收藏  举报