把1-8填入图中的网格中,使得每条线所连接的2个数字不相邻

时间:2021-09-10 08:11:01

把1-8填入图中的网格中,使得每条线所连接的2个数字不相邻

把1-8填入图中的网格中,使得每条线所连接的2个数字不相邻

代码如下:

#include <iostream>
using namespace std;

int isadjoin(int x, int a, int b, int c, int d, int e, int f)
{
if((x != a && x != a-1 && x != a+1) && (x != b && x != b-1 && x != b+1) && (x != c && x != c-1 && x != c+1)
&& (x != d && x != d-1 && x != d+1) && (x != e && x != e-1 && x != e+1) && (x != f && x != f-1 && x != f+1))
return 0;
else
return -1;
}

int isequal(int x, int a, int b, int c, int d)
{
if((x != a) && (x != b) && (x != c)
&& (x != d))
return 0;
else
return -1;
}

int main()
{
int a,b,c,d,e,f,g,x;
for(x = 1; x <= 8; x++)
{
for(a = 1; a <= 8; a++)
{
if(isadjoin(a, x, x, x, x, x, x) == 0 && isequal(a, x, x, x, x) == 0)
for(b = 1; b <= 8; b++)
{
if(isadjoin(b, a, a, a, a, a, a) == 0 && isequal(b, x, x, x, x) == 0)
for(c = 1; c <= 8; c++)
{
if(isadjoin(c, x, a, b, b, b, b) == 0 && isequal(c, a, a, a, a) == 0)
for(d = 1; d <= 8; d++)
{
if(isadjoin(d, a, b, c, c, c, c) == 0 && isequal(d, x, x, x, x) == 0)
for(e = 1; e <= 8; e++)
{
if(isadjoin(e, b, d, d, d, d, d) == 0 && isequal(e, x, a, c, c) == 0)
for(f = 1; f <= 8; f++)
{
if(isadjoin(f, x, c, d, d, d, d) == 0 && isequal(f, a, b, e, e) == 0)
for(g = 1; g <= 8; g++)
{
if(isadjoin(g, c, d, e, f, f, f) == 0 && isequal(g, x, a, b, b) == 0)
cout<<a<<" "<<b<<" \n"<<x<<" "<<c<<" "<<d<<" "<<e<<" \n"<<f<<" "<<g<<"\n\n\n\n"<<endl;
}
}
}
}
}
}
}
}
return 0;
}


答案:

5 3 
2 8 1 7 
6 4

6 4 
2 8 1 7 
5 3

3 5 
7 1 8 2 
4 6

4 6 
7 1 8 2 
3 5