A Famous Grid
Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 190 Accepted Submission(s): 71
Problem Description
Mr. B 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. 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.
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. 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.
Input
Each test case is described by a line of input containing two nonprime integer 1 <=x, y<=10,000.
Output
For each test case, display its case number followed by the length of the shortest path or "impossible" (without quotes) in one line.
Sample Input
1 4 9 32 10 12
Sample Output
Case 1: 1 Case 2: 7 Case 3: impossible
Source
简单的搜索题,比赛的时候范围看错了没敢做。多往外拓展几层然后BFS就可以了。
代码很丑……
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std;
#define MAXN 200
typedef struct
{
int x,y;
}Point;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int map[205][205];
int vis[205][205];
queue <Point> q;
Point p[40005];
int Check(int t)
{
if (t==1) return 1;
for (int i=2;i*i<=t;i++)
{
if (t%i==0) return 1;
}
return -1;
}
int BFS(int x,int y)
{
Point tag,tag1;
int i;
if (x==y) return 0;
vis[p[x].x][p[x].y]=0;
q.push(p[x]);
while(!q.empty())
{
tag=q.front();
q.pop();
for (i=0;i<4;i++)
{
tag1.x=tag.x+dx[i];
tag1.y=tag.y+dy[i];
if (tag1.x>=MAXN || tag1.x<0 || tag1.y>=MAXN || tag1.y<0 || vis[tag1.x][tag1.y]!=-1 || map[tag1.x][tag1.y]==-1) continue;
q.push(tag1);
vis[tag1.x][tag1.y]=vis[tag.x][tag.y]+1;
if (tag1.x==p[y].x && tag1.y==p[y].y) return vis[tag1.x][tag1.y];
}
}
return -1;
}
int main()
{
int t,i,j,n,x,y,d,cnt=1,tag;
d=0;
t=MAXN*MAXN;
x=y=0;
memset(map,0,sizeof(map));
while(t>0)
{
map[x][y]=Check(t);
p[t].x=x;
p[t].y=y;
if (x+dx[d]<0 || x+dx[d]>=MAXN || y+dy[d]<0 || y+dy[d]>=MAXN || map[x+dx[d]][y+dy[d]]!=0)
{
d++;
d%=4;
}
x+=dx[d];
y+=dy[d];
t--;
}
while(scanf("%d%d",&x,&y)!=EOF)
{
printf("Case %d: ",cnt++);
while(!q.empty()) q.pop();
memset(vis,-1,sizeof(vis));
tag=BFS(x,y);
if (tag==-1) printf("impossible\n");
else printf("%d\n",tag);
}
return 0;
}