-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathq1.cpp
More file actions
144 lines (116 loc) · 2.46 KB
/
q1.cpp
File metadata and controls
144 lines (116 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <iostream>
#include <queue>
#include <bitset>
using std::cin;
using std::cout;
using std::endl;
using std::queue;
using std::bitset;
// 1:Flip Game
// 在4x4的方格上,翻转棋子(黑->白,白->黑)
// 每次邻近的四个棋子也会被翻动(如果有的话)
// 最短几次可以全黑或者全白
// unsigned short类型 16位,正好可以存储16个格子的状态
struct State {
unsigned short board;
int count;
State(unsigned short tBoard, int tCount) :board(tBoard), count(tCount) {}
};
bool getPiece(unsigned short board, int i, int j) {
return !((board & (1 << i * 4 + j)) == 0);
}
// test
//void print(unsigned short board) {
// for (int i = 0; i < 4; i++) {
// for (int j = 0; j < 4; j++) {
// bool piece = getPiece(board, i, j);
// if (piece) {
// cout << 'w';
// } else {
// cout << 'b';
// }
// }
// cout << endl;
// }
//}
void flipOne(unsigned short& board, int i, int j) {
if (getPiece(board, i, j)) {
board -= 1 << i * 4 + j;
} else {
board += 1 << i * 4 + j;
}
}
unsigned short flip(unsigned short board, int i, int j) {
flipOne(board, i, j);
if (i > 0) {
flipOne(board, i - 1, j);
}
if (i < 3) {
flipOne(board, i + 1, j);
}
if (j > 0) {
flipOne(board, i, j - 1);
}
if (j < 3) {
flipOne(board, i, j + 1);
}
return board;
}
bool finish(unsigned short board) {
bool piece = getPiece(board, 0, 0);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (getPiece(board, i, j) != piece) {
return false;
}
}
}
return true;
}
int BFS(unsigned short board) {
queue<State> open;
bitset< 1 << 16 > aClose;
// 放入初始棋盘
State state(board, 0);
open.push(state);
aClose[board] = true;
while (!open.empty()) {
State aState = open.front();
open.pop();
if (finish(aState.board)) {
return aState.count;
} else {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
unsigned short temp = flip(aState.board, i, j);
// 判重
if (!aClose[temp]) {
State nextState(temp, aState.count + 1);
open.push(nextState);
aClose[temp] = true;
}
}
}
}
}
return -1;
}
int main(int argc, char *argv[]) {
unsigned short board = 0; // 棋盘
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
char ch;
cin >> ch;
if (ch == 'w') {
board += (1 << (i * 4 + j));
}
}
}
int res = BFS(board);
if (res == -1) {
cout << "Impossible"<<endl;
} else {
cout << res << endl;
}
return 0;
}