首页 > 代码库 > NYOJ592 spiral grid 【BFS】
NYOJ592 spiral grid 【BFS】
spiral grid
时间限制:2000 ms | 内存限制:65535 KB
难度:4
- 描述
- Xiaod has recently discovered the grid named "spiral grid".
Construct the grid like the following figure. (The grid is actually infinite. The figure is only a small part of it.)
Considering traveling in it, you are free to any cell containing a composite number or 1, but traveling to any cell containing a prime number is disallowed. In addition, traveling from a prime number is disallowed, either. You can travel up, down, left or right, but not diagonally. Write a program to find the length of the shortest path between pairs of nonprime numbers, or report it‘s impossible.- 输入
- Each test case is described by a line of input containing two nonprime integer 1 <=x, y<=10,000.
- 输出
- For each test case, display its case number followed by the length of the shortest path or "impossible" (without quotes) in one line.
- 样例输入
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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。