hduoj2553——N皇后問題,dfs回溯

來源:互聯網
上載者:User

標籤:

hduoj 2553  dfs,回溯N皇后問題

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10297    Accepted Submission(s): 4634

Problem Description在N*N的方格棋盤放置了N個皇后,使得它們不相互攻擊(即任意2個皇后不允許處在同一排,同一列,也不允許處在與棋盤邊框成45角的斜線上。
你的任務是,對於給定的N,求出有多少種合法的放置方法。

Input共有若干行,每行一個正整數N≤10,表示棋盤和皇后的數量;如果N=0,表示結束。 Output共有若干行,每行一個正整數,表示對應輸入行的皇后的不同放置數量。 Sample Input1850 Sample Output1 92 10 經典題,題目卡了回溯,打表過了。。關鍵是要以行為單位進行深搜,把vis數組設成int型,vis為0表示可行域,vis=m>0表示在m個棋子的攻擊範圍內,放置棋子或移除棋子是時用增量或減量改變可行域
//題目卡了dfs,所以TLE了。。#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>using namespace std;int map[10][10],cnt,n;void puts(int x,int y){    for(int i=0;i<n;i++){        map[i][y]++;        map[x][i]++;        if(x+y-i<n&&x+y-i>=0) map[i][x+y-i]++;        if(y-x+i<n&&y-x+i>=0) map[i][y-x+i]++;    }}void remove(int x,int y){    for(int i=0;i<n;i++){        map[i][y]--;        map[x][i]--;        if(x+y-i<n&&x+y-i>=0) map[i][x+y-i]--;        if(y-x+i<n&&y-x+i>=0) map[i][y-x+i]--;    }}void search(int cur){    if(cur==n) cnt++;    else{        for(int i=0;i<n;i++){            if(map[i][cur]) continue;            puts(i,cur);            search(cur+1);            remove(i,cur);        }    }}int main(){    while(cin>>n,n){        cnt=0;        memset(map,0,sizeof(map));        search(0);        cout<<cnt<<endl;    }    return 0;}
N皇后問題_dfs打表

 

hduoj2553——N皇后問題,dfs回溯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.