递归版本:
#include
<
iostream
>
#include < vector >
using namespace std;
const int N = 8 ;
int a[N][N];
// 检验是否符合条件
bool check( int n, int i, int j)
... {
int k,l;
for (k=0;k<n;k++)
for (l=0;l<n;l++)
...{
if ((i==k)&&(j==l)) continue;
if (a[k][l]==1)
if ( (abs(i-k)==abs(j-l))||(i==k)||(j==l))
...{
return false;
}
}
return true;
}
void Backtrack( int n, int i)
... {
int j;
if (i>n-1)
...{
for (i=0;i<n;i++)
...{
for (j=0;j<n;j++)
...{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
else
...{
for (j=0;j<n;j++)
...{
a[i][j]=1;
if (check(n,i,j))
...{
Backtrack(n,i+1);
}
a[i][j]=0;
}
}
}
int main()
... {
int i,j;
Backtrack(N,0);
system("pause");
}
#include < vector >
using namespace std;
const int N = 8 ;
int a[N][N];
// 检验是否符合条件
bool check( int n, int i, int j)
... {
int k,l;
for (k=0;k<n;k++)
for (l=0;l<n;l++)
...{
if ((i==k)&&(j==l)) continue;
if (a[k][l]==1)
if ( (abs(i-k)==abs(j-l))||(i==k)||(j==l))
...{
return false;
}
}
return true;
}
void Backtrack( int n, int i)
... {
int j;
if (i>n-1)
...{
for (i=0;i<n;i++)
...{
for (j=0;j<n;j++)
...{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
else
...{
for (j=0;j<n;j++)
...{
a[i][j]=1;
if (check(n,i,j))
...{
Backtrack(n,i+1);
}
a[i][j]=0;
}
}
}
int main()
... {
int i,j;
Backtrack(N,0);
system("pause");
}
非递归版本:
#include
<
iostream
>
#include < vector >
using namespace std;
const int N = 8 ;
int a[N][N];
// 检验是否符合条件
bool check( int n, int i, int j)
... {
int k,l;
for (k=0;k<n;k++)
for (l=0;l<n;l++)
...{
if ((i==k)&&(j==l)) continue;
if (a[k][l]==1)
if ( (abs(i-k)==abs(j-l))||(i==k)||(j==l))
...{
return false;
}
}
return true;
}
void Backtrack( int n)
... {
int i=0;
int j=0;
while(i>=0)
...{
for(; j < n; j++)
...{
a[i][j]=1;
if (check(n, i, j))
...{
if (i>=n-1)
...{
for (int x=0;x<n;x++)
...{
for (int y=0;y<n;y++)
...{
cout<<a[x][y]<<" ";
}
cout<<endl;
}
cout<<endl;
a[i][j]=0;
}
else
...{
i++;
j=-1;
}
}
else
...{
a[i][j]=0;
}
}
i--;
for (j = 0; j < n; j++)//找到上一列排到哪了
if (a[i][j]==1)
...{
a[i][j]=0;
j++;
break;
}
}
}
int main()
... {
int i,j;
Backtrack(N);
system("pause");
}
#include < vector >
using namespace std;
const int N = 8 ;
int a[N][N];
// 检验是否符合条件
bool check( int n, int i, int j)
... {
int k,l;
for (k=0;k<n;k++)
for (l=0;l<n;l++)
...{
if ((i==k)&&(j==l)) continue;
if (a[k][l]==1)
if ( (abs(i-k)==abs(j-l))||(i==k)||(j==l))
...{
return false;
}
}
return true;
}
void Backtrack( int n)
... {
int i=0;
int j=0;
while(i>=0)
...{
for(; j < n; j++)
...{
a[i][j]=1;
if (check(n, i, j))
...{
if (i>=n-1)
...{
for (int x=0;x<n;x++)
...{
for (int y=0;y<n;y++)
...{
cout<<a[x][y]<<" ";
}
cout<<endl;
}
cout<<endl;
a[i][j]=0;
}
else
...{
i++;
j=-1;
}
}
else
...{
a[i][j]=0;
}
}
i--;
for (j = 0; j < n; j++)//找到上一列排到哪了
if (a[i][j]==1)
...{
a[i][j]=0;
j++;
break;
}
}
}
int main()
... {
int i,j;
Backtrack(N);
system("pause");
}