zoj 2050 Flip Game

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1050

 

BFS题.和zoj 2416类似.依次对16个数进行翻转,然后旁边的数也翻转,将翻转以后的状态放到一个数组里,标记为true.然后进入队列.

 

/* * 2050.cpp * * Created on: Apr 29, 2010 * Author: wyy * */ #include<cstdio> #include<queue> using namespace std; char graph[4][5]; bool marked[65536]; int N, State; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; struct point { int state, ret; }; bool IsValid(int x, int y) { return (x >= 0 && x < 4 && y >= 0 && y < 4); } void Init() { State = 0; for(int i = 0; i < 65536; ++i) marked[i] = false; for(int i = 0; i < 4; ++i) { getchar(); scanf("%s", graph[i]); for(int j = 0; j < 4; ++j) if(graph[i][j] == 'b') State |= 1 << (4 * i + j); } } void BFS() { queue<point> Q; bool flag = false; point p1, p2; p1.state = State; p1.ret = 0; marked[p1.state] = true; Q.push(p1); while(!Q.empty()) { p1 = Q.front(); Q.pop(); if(p1.state == 0 || p1.state == 65535) { printf("%d/n", p1.ret); flag = true; break; } for(int i = 0; i < 16; ++i) { p2.state = p1.state ^ (1 << i); for(int j = 0; j < 4; ++j) if(IsValid(i / 4 + dx[j], i % 4 + dy[j])) p2.state ^= (1 << (i + 4 * dx[j] + dy[j])); if(!marked[p2.state]) { marked[p2.state] = true; p2.ret = p1.ret + 1; Q.push(p2); } } } if(!flag) printf("Impossible/n"); if(N) printf("/n"); } int main() { //freopen("input.txt", "r", stdin); scanf("%d", &N); while(N--) { Init(); BFS(); } //fclose(stdin); return 0; }

你可能感兴趣的:(zoj 2050 Flip Game)