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;
}