BFS search + bit operations speed up .. Enumerate each status and perform up, left, down, and right operations ..
When the State is 0 xFFFF or 0, it indicates that all are black or white...
If a status is not accessed, the system enters the queue and marks it as accessed ..
View code
#include <iostream>#include <cstdlib>#include <stdlib.h>#include <string.h>#include <stdio.h>#include <queue>using namespace std;char mp[100];int visit[76000];struct node{ int state;// state value int num; // flip num }p;void bfs( ){ int flag = 0; queue<node>q; q.push(p); visit[p.state] = 1; while( !q.empty() ) { p = q.front(); q.pop( ); node qq; qq.state = p.state; for( int i = 0; i < 16; i++) { p.state = qq.state; p.state = p.state ^ ( 1 << i ); // up if( i >= 4 ) p.state = p.state ^ ( 1 << ( i -4 ) ); // down if( i <= 11 ) p.state = p.state ^ ( 1 << ( i + 4 ) ); // left if( i % 4 != 0 ) p.state = p.state ^ ( 1 << ( i - 1 )); //right if ( (i + 1) % 4 != 0 ) p.state = p.state ^ ( 1 << ( i + 1 ) ); if( p.state == 0xffff || p.state == 0 ) { flag = 1; cout<<p.num + 1 << endl; return; } if( visit[p.state] == 0 ) { node temp; temp.num = p.num + 1; temp.state = p.state; visit[p.state] = 1; q.push(temp); } } } if( !flag ) puts("Impossible");}int main( ){ memset(visit, 0, sizeof(visit)); p.num = 0, p.state = 0; for( int i = 0; i < 16;i++) { cin>>mp[i]; } for( int i = 0; i < 16; i++) { if( mp[i] == 'b' ) p.state += (1<<i); } if( p.state == 0xffff || p.state == 0 ) { puts("0"); } else { bfs( ); } return 0;}