Fill in the grid (again by the full array solution)

Reprinted: https://blog.csdn.net/qq_34202873/article/details/79569451

如图,如下的10个格子,填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)一共有多少种可能的填数方案?
请填写表示方案数目的整数。

Answer: 1580

Insert picture description here
Problem-solving idea:
Use the full arrangement function of C++, and then write a judge function to judge whether the adjacent numbers are continuous. It is more troublesome to write the conditions.

When using the full permutation function, the array elements must be sorted from small to large. Use the do while structure to output all permutations. The initial permutation using the while structure will not output. If the array elements are not sorted from small to large, they cannot output all of them. Full permutation

#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
int a[11]= {11111,0,1,2,3,4,5,6,7,8,9};
int judge()
{
    if(abs(a[1]-a[2])==1||abs(a[1]-a[4])==1||abs(a[1]-a[5])==1||abs(a[1]-a[6])==1)
       return 0;
    else if(abs(a[2]-a[5])==1||abs(a[2]-a[6])==1||abs(a[2]-a[7])==1||abs(a[2]-a[3])==1)
      return 0;
   else if(abs(a[3]-a[6])==1||abs(a[3]-a[7])==1)
     return 0;
  else if(abs(a[4]-a[5])==1||abs(a[4]-a[8])==1||abs(a[4]-a[9])==1)
      return 0;
   else if(abs(a[5]-a[6])==1||abs(a[5]-a[8])==1||abs(a[5]-a[9])==1||abs(a[5]-a[10])==1)
       return 0;
	 else if(abs(a[6]-a[7])==1||abs(a[6]-a[9])==1||abs(a[6]-a[10])==1)
 	   return 0;
 else if(abs(a[7]-a[10])==1)
      return 0;
  else if(abs(a[8]-a[9])==1)
      return 0;
  else if(abs(a[9]-a[10])==1)
     return 0;

    return 1;
}

int main()
{
	int ans=0;
	do
	{      
 	   if(judge())
  	      ans++;
	}while(next_permutation(a+1,a+11));
	printf("%d\n",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/Helinshan/article/details/109057107