POJ-1198(BFS)

来源:互联网 发布:语音识别 python 编辑:程序博客网 时间:2024/05/29 10:09

题目:http://poj.org/problem?id=1198

分析:层次BFS + 状态压缩


#include <cstdio>#include <cstring>#include <cmath>#include <utility>#include <queue>#include <algorithm>using namespace std;typedef pair<int,int> PII;const int walkStep[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};const int jumpStep[4][2] = {{-2, 0}, {2, 0}, {0, -2}, {0, 2}};queue<int> Q;bool vis[1 << 24];PII s[4], e[4];inline bool outOfBorder(int r, int c){return r < 0 || r >= 8 || c < 0 || c >= 8;}bool exist(const PII pos[4], int r, int c){for(int i = 0; i < 4; ++i){if(r == pos[i].first && c == pos[i].second) return true;}return false;}int encode(PII pos[4]){sort(pos, pos + 4);int state = 0;for(int i = 3; i > -1; --i){state = (state << 3) | pos[i].second;state = (state << 3) | pos[i].first;}return state;}void decode(PII pos[4], int state){for(int i = 0; i < 4; ++i){pos[i].first = state & 0x07;  state >>= 3;pos[i].second = state & 0x07; state >>= 3;}}bool walk(const PII cur[4], int i, int d){int r = cur[i].first + walkStep[d][0];int c = cur[i].second + walkStep[d][1];return !outOfBorder(r, c) && !exist(cur, r, c);}bool jump(const PII cur[4], int i, int d){int wr = cur[i].first + walkStep[d][0];int wc = cur[i].second + walkStep[d][1];int jr = cur[i].first + jumpStep[d][0];int jc = cur[i].second + jumpStep[d][1];return !outOfBorder(jr, jc) && exist(cur, wr, wc) && !exist(cur, jr, jc);}int mark(PII nex[4]){int state = encode(nex);if(vis[state]) return -1;vis[state] = true;Q.push(state);return state;}bool bfs(int start, int dest){if(start == dest) return true;while(!Q.empty()) Q.pop();memset(vis, false, sizeof(vis));vis[start] = true;Q.push(start);PII cur[4], nex[4];for(int i = 0; i < 8 && !Q.empty(); ++i){//遍历一层for(int n = Q.size(); n--; ){//得到当前状态的4个位置int state = Q.front(); Q.pop();decode(cur, state);//一步状态扩展for(int j = 0; j < 4; ++j){for(int k = 0; k < 4; ++k){if(walk(cur, j, k)){memcpy(nex, cur, sizeof(cur));nex[j] = PII(cur[j].first + walkStep[k][0], cur[j].second + walkStep[k][1]);if(mark(nex) == dest) return true;}if(jump(cur, j, k)){memcpy(nex, cur, sizeof(cur));nex[j] = PII(cur[j].first + jumpStep[k][0], cur[j].second + jumpStep[k][1]);if(mark(nex) == dest) return true;}}}}}return false;}bool input(){for(int i = 0; i < 4; ++i){if(2 != scanf("%d%d", &s[i].first, &s[i].second)) return false;--s[i].first;--s[i].second;}for(int i = 0; i < 4; ++i){if(2 != scanf("%d%d", &e[i].first, &e[i].second)) return false;--e[i].first;--e[i].second;}return true;}int main(){    while(input()){    if(bfs(encode(s), encode(e))) puts("YES");    else puts("NO");    }    return 0;}

0 0