# Queen P1219 of Luogu (dfs + retrospective method)

Keywords: PHP

https://www.luogu.org/problem/P1219

Topic: Each row, each column and only one, each diagonal line (including all parallel lines of two principal diagonals) has at most one chess piece and outputs the first three schemes of all schemes.

In each scenario, the search starts from the first line, one line by one line, the abscissa will not repeat, so it only needs to mark the longitudinal coordinates; from the upper right to the lower left diagonals and their parallel lines, it will be found that the sum of the abscissa and longitudinal coordinates is equal; from the upper left to the lower right diagonals and their parallel lines, it will be found that the difference between the abscissa and vertical coordinates is equal, (x-y) may be negative. x-y+n;

```// luogu-judger-enable-o2
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <cstring>
#include <map>
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
typedef long long lll;
const int maxn = 200005;
const lll INF = 0x3f3f3f3f3f;
int ans,vis1,vis2,vis3,n,m;
void output()
{
m++;
if(m <= 3)//Output only the first three schemes
{
for(int i=1; i<=n; i++)
{
cout << ans[i];
if(i < n) cout << " ";
else cout << endl;
}
}
}
void dfs(int i)
{
if(i>n)
{
output();//The current number of rows is greater than n Line scheme satisfies requirement output
}
else
{
for(int j = 1; j <= n; j++)//Number of columns corresponding to each row
{
if(!vis1[j]&&!vis2[i+j]&&!vis3[i-j+n])//Vertical coordinates and two diagonals satisfy
{
ans[i] = j;
vis1[j] = 1;
vis2[i+j] = 1;
vis3[i-j+n] = 1;//Marking indicates that the current solution is in use
dfs(i+1);//Search for another line
vis1[j] = 0;
vis2[i+j] = 0;
vis3[i-j+n] = 0;//Mark back the next scenario that can be used
}
}
}
}
int main()
{
cin >> n;
dfs(1);//Search from the first line
cout << m;
return 0;
}```

Posted by kritro on Fri, 11 Oct 2019 11:32:02 -0700