标签:nyoj592
1 4 9 32 10 12
Case 1: 1 Case 2: 7 Case 3: impossible
#include <stdio.h> #include <math.h> #include <string.h> #include <queue> #define abs(a) (a) > 0 ? (a) : -(a) using std::queue; int map[102][102], vis[102][102], prime[10002] = {1, 1}; int x, y, mov[][2] = {0, 1, 0, -1, 1, 0, -1, 0}; struct Node{ int x, y, steps; }; queue<Node> Q; void preprocess(){ //画图的时候要细心 int count = 10000, x = 2, y = 2; for(int i = 1; i <= 100; ++i) map[1][i] = count--; for(int i = 2; i <= 100; ++i) map[i][100] = count--; for(int i = 99; i > 0; --i) map[100][i] = count--; for(int i = 99; i > 1; --i) map[i][1] = count--; map[2][2] = count--; while(count > 0){ while(!map[x][y+1]) map[x][++y] = count--; while(!map[x+1][y]) map[++x][y] = count--; while(!map[x][y-1]) map[x][--y] = count--; while(!map[x-1][y]) map[--x][y] = count--; } } Node getX(){ Node t = {0}; for(int i = 1; i < 101; ++i) for(int j = 1; j < 101; ++j){ if(map[i][j] == x){ t.x = i; t.y = j; return t; } } } void getPrime(){ for(int i = 2; i <= 100; ++i){ if(prime[i]) continue; for(int j = i * i; j <= 10000; j += i) prime[j] = 1; } } int check(Node t){ if(t.x < 1 || t.y < 1 || t.x > 100 || t.y > 100) return 0; if(vis[t.x][t.y] || !prime[map[t.x][t.y]]) return 0; return 1; } void BFS(){ Node temp, now; while(!Q.empty()) Q.pop(); now = getX(); if(x == y){ printf("0\n"); return; } Q.push(now); while(!Q.empty()){ now = Q.front(); Q.pop(); for(int i = 0; i < 4; ++i){ temp = now; temp.x += mov[i][0]; temp.y += mov[i][1]; ++temp.steps; if(check(temp)){ if(map[temp.x][temp.y] == y){ printf("%d\n", temp.steps); return; } vis[temp.x][temp.y] = 1; Q.push(temp); } } } printf("impossible\n"); } int main(){ getPrime(); preprocess(); int times = 1; while(scanf("%d%d", &x, &y) == 2){ printf("Case %d: ", times++); memset(vis, 0, sizeof(vis)); BFS(); } return 0; }
NYOJ592 spiral grid 【BFS】,布布扣,bubuko.com
标签:nyoj592
原文地址:http://blog.csdn.net/chang_mu/article/details/32335611