Luo Gu P1219 Eight Queens me. . . . . .

Code 1    (school brother version)

#include <bits / STDC ++ H.>
the using namespace STD;
int L [15];
BOOL S [15]; // SAD determines whether the same function slash, abs () represents an absolute value
bool sad (int x, int i) {// x is the current line, i is the current position of the line pieces
 for (int j = 1; j <x; j ++) {// j before line L [j] indicates the position of the j-th row
  if (abs (xj) == abs (il [j])) return false; // if on the same diagonal lines, the line - a row = absolute value of the previous column - the absolute value of the column
 }
 return to true;
}
int n-, CNT;
void Print () {
 for (int I =. 1; I <= n-; I ++)
  COUT << L [I] << "";
 COUT << endl; // wrap
}
inline void DFS ( X int) {
         // X COUT << << endl; Debug part
 IF (n-X == +. 1) {
  ++ CNT;
  IF (CNT <=. 3)
   Print ();
  return;
 }
 for (int i = 1; i <= n; i ++) {// x is the current line, i is the position of the current row
  if (! s [i] || sad (x, i)) // if at the same ramp line, then the line - the absolute value of the previous row = row - the absolute value of the column
   Continue;
          // << COUT "asdawe" << endl; Debug portion
  S [I] = to true;
  L [X] = I;
  DFS (X +. 1);
  S [I] to false =;
  L [X] = 0;
 }
}
int main () {
 CIN n->>;
 DFS (. 1);
 COUT << CNT;
 return 0;
}

 

Code 2 seniors edition! !

#include<bits/stdc++.h>
using namespace std;
int N;
int chess[15];
bool flag[100];
int all = 0;
bool isUseful(int num,int locate) {
 for(int i = 1; i<locate; i++)
  if(abs(chess[i] - num) ==  (locate-i))
   return false;
 return true;
}
void print() {
 for(int i = 1; i<=N; i++)
  cout << chess[i] << " ";
 cout << endl;
}
void dfs(int num) {
 if(num==N+1) {
  all++;
  if(all<=3)
   print();
  return;
 }
 for(int i = 1; i<=N; i++) {
  if(!flag[i] && isUseful(i,num)) {
   chess[num] = i;
   flag[i] = true;
   dfs(num+1);
   flag[i] = false;
  }
 }
}
int main() {
 cin >> N;
 dfs(1);
 cout << all <<endl;
 return 0;
}
 
 
代码3  王某人版
#include<cstdio>
#include<cstring>
int r[15], c[15], zd[30], cd[30],cnt;
int n;
void print(){
 for (int i = 1; i <= n; ++i)
  printf("%d ", r[i]);
 puts("");
}
inline void dfs(int x){
 if (x == n + 1){
  ++cnt;
  if (cnt <= 3)
   print();
  return;
 }
 for (int i = 1; i <= n; ++i){
  if (c[i] || zd[x - i + n + 1] || cd[i + x])
   continue;
  c[i] = zd[x - i + n + 1] = cd[i + x] = 1;
  r[x] = i;
  dfs(x + 1);
  c[i] = zd[x - i + n + 1] = cd[i + x] = 0;
  r[x] = 0;
 }
}
int main(){
 scanf("%d", &n);
 dfs(1);
 printf("%d", cnt);
 return 0;
}

Guess you like

Origin www.cnblogs.com/QingyuYYYYY/p/11621945.html