1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import java.util.*;
public class OJ58 { static int[][] walked =new int[9][9]; static Queue<location> queue = new LinkedList<location>();
static int[][] map={{1,1,1,1,1,1,1,1,1}, {1,0,0,1,0,0,1,0,1}, {1,0,0,1,1,0,0,0,1}, {1,0,1,0,1,1,0,1,1}, {1,0,0,0,0,1,0,0,1}, {1,1,0,1,0,1,0,0,1}, {1,1,0,1,0,1,0,0,1}, {1,1,0,1,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1}};
public static void main(String[] args) { Scanner in =new Scanner(System.in); int n = in.nextInt(); for (int i = 0; i < n; i++) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); int d = in.nextInt();
if (a == c && b == d) { System.out.println(0); continue; } move(a, b,0); while (queue.size() != 0) { location laca = queue.poll();
if (laca.x == c && laca.y == d) { System.out.println(laca.step); queue.clear(); for (int w = 0; w < 9; w++) { Arrays.fill(walked[w], 0); }
break; } else { move(laca.x,laca.y, laca.step); } } } }
private static void move(int x, int y, int steps) {
ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(-1); for (int i : list) { if (x + i > -1 && x + i <= 8 && walked[x + i][y] == 0 && map[x + i][y] == 0) { walked[x + i][y] = 1; location laca = new location(); laca.x = x + i; laca.y = y; laca.step =steps+1; queue.offer(laca); } } for (int i : list) { if (y + i > -1 && y + i <= 8 && walked[x][y + i] == 0 && map[x][y + i] == 0) { walked[x][y + i] = 1; location laca = new location(); laca.x = x; laca.y = y+i; laca.step = steps+1; queue.offer(laca); } } }
}
class location { int x; int y; int step; }
|