4*4的棋盘,棋盘上的每个位置都是黑或白,每个位置的颜色可以翻转,并且翻转一个位置的同时其周围的棋子的颜色也同时翻转。给一个目标状态,问多少步可以到达目标状态。 广度优先搜索。 #include <stdio.h> #include <queue> using namespace std; struct STATE { bool map[4][4]; int step; }; STATE s; queue<STATE> q; bool visited[65536]; int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0}; int getstate(STATE t) { int ans = 0, i, j; for (i=0; i<4; i++) for (j=0; j<4; j++) { if (t.map[i][j]) ans |= 1<<(i*4+j); } return ans; } void bfs() { int i, j, d, mask; int x, y; STATE cur, next; s.step = 0; q.push(s); memset(visited, 0, sizeof(visited)); mask = getstate(s); visited[mask] = true; while (!q.empty()) { cur = q.front(); q.pop(); mask = getstate(cur); if (mask==0 || mask+1 == 65536) { printf("%d/n", cur.step); return; } for (i=0; i<4; i++) for (j=0; j<4; j++) { next = cur; next.step++; next.map[i][j] = !next.map[i][j]; for (d=0; d<4; d++) { x = i + dir[d][0]; y = j + dir[d][1]; if (x>=0 && x<4 && y>=0 && y<4) next.map[x][y] = !next.map[x][y]; } mask = getstate(next); if (!visited[mask]) { q.push(next); visited[mask] = true; } } } printf("Impossible/n"); } int main() { int i, j; char ch; //freopen("data.txt", "r", stdin); for (i=0; i<4; i++) { for (j=0; j<4; j++) { scanf("%c", &ch); if (ch == 'b') s.map[i][j] = true; else s.map[i][j] = false; } scanf("%c", &ch); } bfs(); return 0; }