coder_new

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

DFS+状态位

View Code
 1  #include<iostream>
 2  using namespace std;
 3  
 4  int chess=0;        
 5  int step;
 6  bool flag=false;
 7  int ri[16],cj[16];
 8  
 9  bool isopen(void)
10  {
11      if(chess==0xFFFF)
12          return true;
13      else
14          return false;
15  }
16  
17  void flip(int bit)
18  {
19      chess=chess^(1<<bit);  
20      int row=bit/4;
21      int col=bit%4;
22      for(int c=0;c<4;c++)
23          chess=chess^(1<<(row*4+c));  
24      for(int r=0;r<4;r++)
25          chess=chess^(1<<(r*4+col));  
26      return;
27  }
28  
29  void dfs(int bit,int deep)
30  {
31      if(deep==step)
32      {
33          flag=isopen();
34          return;
35      }
36  
37      if(flag||bit>15)return;
38  
39      ri[deep]=bit/4;
40      cj[deep]=bit%4;
41  
42      flip(bit);
43      dfs(bit+1,deep+1);
44 
45      flip(bit);
46      dfs(bit+1,deep);
47      return;
48  }
49  
50  int main(void)
51  {
52      char ch;
53      for(int i=0;i<4;i++)
54          for(int j=0;j<4;j++)
55          {
56              cin>>ch;
57              if(ch=='-') chess=chess^(1<<(i*4+j));
58          }
59 
60      for(step=0;step<=16;step++)
61      {
62          dfs(0,0);
63          if(flag) break;
64      }
65  
66      cout<<step<<endl;
67      for(int i=0;i<step;i++)
68          cout<<ri[i]+1<<' '<<cj[i]+1<<endl;
69      return 0;
70  }

 

 

posted on 2012-05-08 11:44  coder_new  阅读(154)  评论(0编辑  收藏  举报