1 条题解
-
0
C :
#include <stdio.h> #include <string.h> #include <stdlib.h> main() { int time,times[8][8]={0, 3, 2, 3, 2, 3, 4, 5, 3, 2, 1, 2, 3, 4, 3, 4, 2, 1, 4, 3, 2, 3, 4, 5, 3, 2, 3, 2, 3, 4, 3, 4, 2, 3, 2, 3, 4, 3, 4, 5, 3, 4, 3, 4, 3, 4, 5, 4, 4, 3, 4, 3, 4, 5, 4, 5, 5, 4, 5, 4, 5, 4, 5, 6}; char x[3],y[3]; while(scanf("%s%s",&x,&y)!=EOF) { if((strcmp(x,"a1\0")==0 && strcmp(y,"b2\0")==0)||(strcmp(x,"a8\0")==0 && strcmp(y,"b7\0")==0)||(strcmp(x,"h1\0")==0 && strcmp(y,"g2\0")==0)||(strcmp(x,"h8\0")==0 && strcmp(y,"g7\0")==0)||(strcmp(x,"b2\0")==0 && strcmp(y,"a1\0")==0)||(strcmp(x,"b7\0")==0 && strcmp(y,"a8\0")==0)||(strcmp(x,"g2\0")==0 && strcmp(y,"h1\0")==0)||(strcmp(x,"g7\0")==0 && strcmp(y,"h8\0")==0)) { time=4; } else { time=times[abs(x[0]-y[0])][abs(x[1]-y[1])]; } printf("To get from %s to %s takes %d knight moves.\n",x,y,time); } return 0; }
Java :
import java.util.LinkedList; import java.util.Scanner; public class Main { static int[][] to = { { -1, -2 }, { -2, -1 }, { -2, 1 }, { -1, 2 }, { 1, 2 }, { 2, 1 }, { 2, -1 }, { 1, -2 } }; public static void main(String[]args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { boolean vis[][] = new boolean[9][9]; int time = 0; String s = in.next(); String e = in.next(); int sx = s.charAt(0) - 'a'+1; int sy = s.charAt(1) -48; int ex = e.charAt(0) - 'a'+1; int ey = e.charAt(1) -48; point p = new point(sy,sx); vis[sy][sx] = true; LinkedList<point> list1 = new LinkedList<point>(); LinkedList<Integer> list2 = new LinkedList<Integer>(); list1.add(p); list2.add(0); while(!list1.isEmpty()) { point p1 = list1.poll(); time = list2.poll(); if(p1.x == ey && p1.y==ex) break; for(int i = 0;i<8;i++) { int a = p1.x+to[i][0]; int b = p1.y+to[i][1]; if(a>0 && b>0 && a<9 && b<9 && !vis[a][b]) { point p2 = new point(a,b); list1.add(p2); list2.add(time+1); vis[a][b] = true; } } } System.out.println("To get from "+s+" to "+e+" takes "+time+" knight moves."); } } } class point { int x; int y; point(int a,int b) { x = a; y = b; } }
- 1
信息
- ID
- 1657
- 时间
- 1000ms
- 内存
- 32MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者