1. 程式人生 > 實用技巧 >E. Graph Coloring dp+圖論 or 思維

E. Graph Coloring dp+圖論 or 思維

型別:dfs()搜尋,是 n皇后問題的擴充套件,可以先放置白皇后,待到白皇后放置完畢之後開始放置黑皇后,黑白皇后全都放置完畢,答案+1;

知識點:關於兩點是否位於同一條對角線上 對於點(x,y)和點(a,b) 如果abs(a-x)==abs(b-y) 說明兩點位於一條對角線上,類似於矩形的對角線。

參考程式碼:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<cmath>
 5 using namespace std;
 6 const
int N=10; 7 int mat[N][N]; 8 int n; 9 int ans; 10 int white_location[N],black_location[N];//儲存白皇后和黑皇后放棋子在第i行放棋子的位置 11 bool white_check(int row,int conlumn) //符合白皇后的放置規則 12 { 13 for(int i=1;i<row;i++) 14 { 15 if(conlumn==white_location[i]||abs(row-i)==abs(conlumn-white_location[i]))//
如果這個列放置了白皇后或者對角線放置了白皇后 16 return false; 17 } 18 return true; 19 } 20 bool black_check(int row,int conlumn) 21 { 22 for(int i=1;i<row;i++) 23 { 24 if(conlumn==black_location[i]||abs(row-i)==abs(conlumn-black_location[i])) 25 return false; 26 } 27
return true; 28 } 29 void black_dfs(int row) 30 { 31 if(row==n+1) 32 { 33 ans++; 34 return; 35 } 36 for(int j=1;j<=n;j++) 37 { 38 if(mat[row][j]==0||j==white_location[row]) continue; 39 if(black_check(row,j)) 40 { 41 black_location[row]=j; 42 mat[row][j]=0; 43 black_dfs(row+1); 44 mat[row][j]=1; 45 black_location[row]=0; 46 } 47 } 48 } 49 void white_dfs(int row) //白皇后放置 50 { 51 if(row==n+1) 52 { 53 black_dfs(1); //去放置黑皇后 54 return; 55 } 56 for(int j=1;j<=n;j++) 57 { 58 if(mat[row][j]==0) continue; 59 if(white_check(row,j)) 60 { 61 white_location[row]=j;//標記 62 mat[row][j]=0; 63 white_dfs(row+1); 64 mat[row][j]=1; //回溯 65 white_location[row]=0; 66 } 67 } 68 } 69 70 int main() 71 { 72 scanf("%d",&n); 73 for(int i=1;i<=n;i++) 74 for(int j=1;j<=n;j++) 75 scanf("%d",&mat[i][j]); 76 white_dfs(1); 77 printf("%d",ans); 78 return 0; 79 }
View Code