zoj 1649 Rescue

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

 

BFS题.纠结了很久.这题不是无权最短路径的题.而是有权的.然后就用一般的BFS做了,WA多次.后来看了别人的解题报告才知道处理guard时

 

要分别对待.

 

/* * 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 1649 Rescue)