2016蓝桥杯方格填空题

方格填数

填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)

一共有多少种可能的填数方案?

请填写表示方案数目的整数。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字


首先根据题目分析:
这是一道搜索题目,那么考虑dfs或者bfs解题。
先考虑用dfs解题:
用为伪代码写好基本的思路框架如下:
dfs() //从(0,1)开始一行一行搜索到(2.3)结束。
{
  //考虑结束条件
  if到达最后一个格子
  count++;

  for0-9//每个数都考虑能不能填在当前方格
  {
    if这个数没有被用过 && 相邻的格子的数和这个数不连续
    {
      填入这个数;
      并且做状态标记;
      dfs(下一个格子的坐标,填入的数)
      回溯标记;
    }
  }  
}

代码如下:

 1 #include <iostream>
 2 #include <string.h>
 3 using namespace std;
 4 const int INF = 99999;
 5 const int end_x = 2;
 6 const int end_y = 3;
 7 int count=0;
 8 int map[end_x+1][end_y+1];
 9 int num[10];
10 int d_x[8] = {1,1,0,-1,-1,-1,0,1};
11 int d_y[8] = {0,1,1,1,0,-1,-1,-1};
12 bool can_fill(int x,int y,int n)
13 {
14     for(int i=0;i<8;i++)
15     {
16         int nx = x+d_x[i];
17         int ny = y+d_y[i];
18         if (nx >= 0 && nx <= end_x && ny >= 0 && ny <= end_y) {
19             if (map[nx][ny] == n - 1 || map[nx][ny] == n + 1) {
20                 return false;
21             }
22         }
23     }
24     return true;
25 } 
26 
27 void dfs(int x,int y)
28 {
29     if(x==end_x && y==end_y)
30     {
31         count++;
32         return;
33     }
34     if(y>end_y)
35     {
36         dfs(x+1,0); //如果到达行末 
37     }
38     else
39     {
40             for(int i=0;i<=9;i++)
41             {
42                 if(num[i]==0 && can_fill(x,y,i))
43                 {
44                     num[i]=1;map[x][y]=i;
45                     dfs(x,y+1);
46                     num[i]=0;map[x][y]=INF;
47                 }
48             }
49     }
50 }
51 
52 int main()
53 {
54     memset(num, 0, sizeof(num));
55     for (int i = 0; i <= end_x; i++) 
56     {
57         for (int j = 0; j <= end_y; j++) 
58         {
59             map[i][j] = INF;
60         }
61     }
62     dfs(0, 1); 
63     cout << count << endl; 
64     return 0;
65 }

猜你喜欢

转载自www.cnblogs.com/ncuzhangqiang/p/10541378.html
今日推荐