1 #include <iostream> 2 #include <cstring> // memset(), memcpy header file 3 using namespace std; 4 5 // Get the jth bit 6 int Getbit( int num, int j) 7 { 8 return (num >> j)& 1 ; 9 } 10 // Set the jth bit 11 void Setbit( char & num, int j, int s) 12 { 13 if (s) 14 num |= ( 1 << j); 15 else 16 num &= ~( 1 << j); 17 } 18 // Invert the jth bit 19 void Flipbit( char & num, int j) 20 { 21 num ^ = ( 1 << j); 22 } 23 24 int main( int argc, char * argv[]) 25 { 26 char orilight[ 5 ]; // original light status 27 char curlight[ 5 ]; // Current light status 28 char result[ 5 ]; // Result 29 int switches; // Switch status 30 bool flag = false ; // Determine whether there is a result 31 32 // Initialize the original light state 33 memset(orilight, 0 , sizeof (orilight)); 34 for ( int i = 0 ;i < 5 ;++ i) 35 for ( intj = 0 ;j < 6 ;++ j) 36 { 37 int single; 38 cin >> single; 39 Setbit(orilight[i],j,s); 40 } 41 // determine result 42 for ( int n = 0 ;n < 64 ;++ n) 43 { 44 switches = n; 45 memcpy(curlight,orilight, sizeof (orilight)); // Save the state of the original light to the current light matrix every time an enumeration is performed 46 //To ensure that each test result will not change the original state 47 // Process the state of each row of lights 48 for ( int i = 0 ;i < 5 ;++ i) 49 { 50 result[i] = switches; 51 for ( int j = 0 ;j < 6 ;++ j) 52 { 53 if (Getbit(switchs,j)) 54 { 55 if (j > 0 ) 56 Flipbit(curlight[i],j - 1 ); 57 Flipbit(curlight[i],j); 58 if (j < 5 ) 59 Flipbit(curlight[i],j+ 1 ); 60 } 61 } 62 // Process the state of the i+1 row light 63 if (j < 4 ) 64 curlight[i+ 1 ] ^= switches; 65 switches = curlight[i]; 66 } 67 // When the light in the fifth row is off, find the result 68 if (curlight[ 4 ] == 0) 69 { 70 flag = true; 71 break; 72 } 73 } 74 if(flag) 75 { 76 for(int i = 0;i < 5;++i) 77 { 78 for(int j = 0;j < 6;++j) 79 { 80 cout << Getbit(result[i],j) << " "; 81 } 82 cout << endl; 83 } 84 } 85 else 86 cout << "no anwser" << endl; 87 88 return 0; 89 }
Supplement: For the required number of enumerations, we can calculate it like this: because we only need to enumerate the states of the lamps in the first row, and there are 6 lamps in the first row, the full arrangement is 2 6 types, that is, we only need to Enumerate 64 times.
Of course, we can also enumerate fewer times, that is, only enumerate 32 times (2 5 ), and enumerate by column. This method can consider using a char array of size 6, each array stores one column, and the other Process
Such as enumeration by row.