Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 27237 | Accepted: 11816 |
Description
- Choose any one of the 16 pieces.
- Flip the chosen piece and also all adjacent pieces to the left, to the right, to the top, and to the bottom of the chosen piece (if there are any).
Consider the following position as an example:
bwbw
wwww
bbwb
bwwb
Here "b" denotes pieces lying their black side up and "w" denotes pieces lying their white side up. If we choose to flip the 1st piece from the 3rd row (this choice is shown at the picture), then the field will become:
bwbw
bwww
wwwb
wwwb
The goal of the game is to flip either all pieces white side up or all pieces black side up. You are to write a program that will search for the minimum number of rounds needed to achieve this goal.
Input
Output
Sample Input
bwwb bbwb bwwb bwww
Sample Output
4
“异或”运算符(^)
他的规则是:若参加运算的两个二进制位值相同则为0,否则为1
即0∧0=0,0∧1=1,1∧0=1, 1∧1=0
例: 00111001
∧ 00101010
00010011
c语言源代码:
#include <stdio.h>
main()
{
int a=071;
int b = 052;
printf("%d",a^b);
}
应用:
使特定位翻转,与1异或
设有数01111010(2),想使其低4位翻转,即1变0,0变1.可以将其与00001111(2)进行“异或”运算,
即:
01111010
^00001111
01110101
运算结果的低4位正好是原数低4位的翻转。可见,要使哪几位翻转就将与其进行∧运算的该几位置为1
即可。
#include<stdio.h>
#include<iostream>
#include<queue>
#define N 4
using namespace std;;
typedef struct{
int step;
int state;
}node;
queue<node> q;
int d[4][2] = {{0,1}, {1,0}, {-1,0}, {0,-1}};
int a[16] = {0};
int start;
int visited[70000];//2的16次方65536
void inita(){
int i, j, k ;
int x, y;
int count = 0;
int temp;
for(i = 0; i < N; i++)
for(j = 0; j < N; j++){//给每个状态赋值,一共是2^16个状态
temp = 0;
temp = 1 << (3-i) * 4 + (3-j);//给后面的行,列填零
for(k = 0; k < 4; k++){
x = i + d[k][0];
y = j + d[k][1];
if(x >= 0 && y >= 0 && x < N && y < N)
temp = temp ^ (1 << (3-x)*4 + (3-y));//某位数及其会翻转的结果
}
a[count++] = temp;
}
}
void read_data(){
int i, j;
char str[N];
start = 0;
for(i = 0; i < N; i++){
scanf("%s", str);
for(j = 0; j < N; j++){
start <<= 1;
if(str[j] == 'b')
start += 1;
}
}
}
void bfs(){
node curr, next;
int i;
while(!q.empty()){
curr = q.front();
q.pop();
// printf("%d %x\n", curr.step , curr.state);
// getchar();
if(curr.state == 0xffff || curr.state == 0){
printf("%d\n", curr.step);
return;
}
for(i = 0; i < N * N; i++){
next.state = curr.state ^ a[i];
if(visited[next.state] == 0){
visited[next.state] = 1;
next.step = curr.step + 1;
q.push(next);
}
}
}
printf("Impossible\n");
}
int main(){
node b;
inita();
read_data();
while(!q.empty())
q.pop();
b.step = 0;
b.state = start;
q.push(b);
bfs();
return 0;
}