题意:给你一个立方体,其中有16个顶点,每个顶点有4个顶点相邻。每个顶点有一个开关,其中给你8开(1)8关(0),让你交换一条边上两点开光状态,使得编号1-8的开光全关。求出达到要求的最小步数。如果大于3则输出more。。

解题思路:首先用map存储图的状况,对前八个编号为开的每个顶点进行dfs,如果相邻点状态为1,则没必要继续dfs,如果为0,则dfs,一直到dfs到顶点的序号大于等于9,更新本点的最小步数的顶点。最后 求和即可

解题代码:

HDU 3220 Alice’s Cube_编程题目HDU 3220 Alice’s Cube_dfs_02
  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <stdio.h>
  4 
  5 
  6 int map[10][5];
  7 int a[20];
  8 int visit[20];
  9 int s;
 10 int ans;
 11 int ok;
 12 void dfs(int k , int step)
 13 {
 14    //printf("%d\n",k);
 15    if(k >= 9)
 16    {
 17         ok = 1;
 18        if(step < s)
 19         {
 20         //  printf("**%d\n",step);
 21           s = step;
 22           ans = k;
 23         }
 24        return ;
 25    }
 26    for(int i = 1;i <= 4; i ++)
 27    {
 28       if(a[map[k][i]] == 0  && !visit[map[k][i]])
 29         {  
 30             visit[map[k][i]] = 1;
 31             dfs(map[k][i],step +1 );
 32             visit[map[k][i]] = 0;
 33         }
 34    }
 35 
 36 }
 37 int main()
 38 {
 39     //    for(int i = 1;i <= 8; i ++)
 40     //    for(int j= 1;j <= 4; j ++)
 41     //    printf("map[%d][%d] =  ;\n",i,j);
 42         map[1][1] = 2 ;
 43         map[1][2] = 3 ;
 44         map[1][3] = 9 ;
 45         map[1][4] =  5;
 46         map[2][1] = 1 ;
 47         map[2][2] = 4 ;
 48         map[2][3] = 6 ;
 49         map[2][4] = 10 ;
 50         map[3][1] = 1 ;
 51         map[3][2] = 7 ;
 52         map[3][3] = 4 ;
 53         map[3][4] = 11 ;
 54         map[4][1] = 3 ;
 55         map[4][2] = 2 ;
 56         map[4][3] =  12;
 57         map[4][4] =  8;
 58         map[5][1] =1  ;
 59         map[5][2] = 6 ;
 60         map[5][3] =  13;
 61         map[5][4] =  7;
 62         map[6][1] = 2 ;
 63         map[6][2] = 5 ;
 64         map[6][3] =  8;
 65         map[6][4] =  14;
 66         map[7][1] =  3;
 67         map[7][2] =  15;
 68         map[7][3] =  5;
 69         map[7][4] =  8;
 70         map[8][1] =  7;
 71         map[8][2] =  6;
 72         map[8][3] =  16;
 73         map[8][4] =  4;
 74         
 75     int n ;
 76     scanf("%d",&n);
 77     for(int cs = 1;cs <= n; cs ++)
 78     {
 79         
 80         
 81         for(int i = 1;i <= 16; i ++)
 82         {
 83           scanf("%d",&a[i]);
 84         }
 85         printf("Case #%d: ",cs);
 86         int sum = 0 ;
 87         for(int i = 1;i <= 8 ;i ++)
 88         {
 89           if(a[i])
 90           {
 91              s = 4; 
 92             memset(visit,0,sizeof(visit));
 93             visit[i] = 1;
 94             ok =0 ;
 95             dfs(i,0);
 96             visit[i] = 0;
 97             if(ok)
 98             {
 99               a[i] = 0 ;
100               a[ans] = 1;
101             }
102             sum += s;
103           }
104           if(sum > 3)
105               break;
106         }
107         if(sum > 3 )
108             printf("more\n");
109         else printf("%d\n",sum);
110     }
111   return 0 ; 
112 }
View Code