描述
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.
1 4 9 32 10 12
Case 1: 1 Case 2: 7 Case 3: impossible
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; class node { int x,y,step; public node(int x,int y,int step) { // TODO Auto-generated constructor stub this.x=x; this.y=y; this.step=step; } } public class Main { static int map[][],startx,starty,endx,endy,n=40400,size=210; static boolean prim[],mark[][],vis[][]; static int directions[][]={{-1,0},{1,0},{0,-1},{0,1}}; public static void isprim() { prim[1]=true; for(int i=2;i*i<=10009;i++) { if(!prim[i]) { for(int j=2*i;j<=10009;j+=i) { prim[j]=true; } } } } public static void constructmap() { int data=40000; int x=200; map[0][0]=data; int i=0,k=0; while(data>1) { while(k<x-1&&map[i][k+1]==0)map[i][k++]=data--; while(i<x-1&&map[i+1][k]==0)map[i++][k]=data--; while(k>0&&map[i][k-1]==0)map[i][k--]=data--; while(i>0&&map[i-1][k]==0)map[i--][k]=data--; } map[i][k]=1; } public static boolean overmap(int x,int y) { if(x<0||x>=200||y<0||y>=200)return true; return false; } public static int bfs(int x,int y) { if(x==y)return 0; //注意终点不可以是素数 if(!prim[y]) return -1; node first=new node(startx, starty, 0); Queue<node>queue=new LinkedList<node>(); queue.add(first); while(!queue.isEmpty()) { first=queue.remove(); vis[first.x][first.y]=true; for(int i=0;i<4;i++) { node next=new node(first.x+directions[i][0], first.y+directions[i][1],first.step+1); if(next.x==endx&&next.y==endy)return next.step; if(overmap(next.x,next.y)||!prim[map[next.x][next.y]]||vis[next.x][next.y])continue; queue.add(next); vis[next.x][next.y]=true; } } return -1; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); map=new int[size][size]; prim=new boolean[n]; constructmap(); isprim(); int count=1; while(scanner.hasNext()) { vis=new boolean[size][size]; int x=scanner.nextInt(); int y=scanner.nextInt(); for(int i=0;i<200;i++) { for(int j=0;j<200;j++) { if(map[i][j]==x) { startx=i; starty=j; } if(map[i][j]==y) { endx=i; endy=j; } } } System.out.printf("Case %d: ",count++); int result=bfs(x,y); if(result==-1) System.out.println("impossible"); else { System.out.println(result); } } } }