Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2014
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3.  
  4. public class CaptureThemAll
  5. {
  6.  
  7.     int n = 8;
  8.     int dx[] = new int[]
  9.     { -2, -2, 2, 2, -1, 1, -1, 1 };
  10.     int dy[] = new int[]
  11.     { -1, 1, -1, 1, -2, -2, 2, 2 };
  12.  
  13.     public int fastKnight(String knight, String rook, String queen)
  14.     {
  15.         // convert to posititions
  16.         Pos s = new Pos(knight, 0);
  17.         Pos t1 = new Pos(rook, 0);
  18.         Pos t2 = new Pos(queen, 0);
  19.  
  20.         // find all distances
  21.         int st1 = bfs(s, t1);
  22.         int st2 = bfs(s, t2);
  23.         int t1t2 = bfs(t1, t2);
  24.        
  25.         System.out.println(st1 + " " + st2 + " " + t1t2);
  26.  
  27.         // find min
  28.         int poss[] = new int[]{2 * st1 + st2, 2 * st2 + st1, st1 + t1t2, st2 + t1t2};
  29.         int min = Integer.MAX_VALUE;
  30.         for (int i = 0; i < poss.length; i++)
  31.             min = Math.min(min, poss[i]);
  32.         return min;
  33.     }
  34.  
  35.     private int bfs(Pos s, Pos t)
  36.     {
  37.         // invariants
  38.         boolean visited[][] = new boolean[n][n];
  39.         Queue<Pos> q = new LinkedList<Pos>();
  40.         s.dist = 0;
  41.         q.add(s);
  42.  
  43.         // bfs
  44.         while (!q.isEmpty())
  45.         {
  46.             // poll
  47.             Pos pos = q.poll();
  48.             visited[pos.r][pos.c] = true;
  49.             if (pos.r == t.r && pos.c == t.c)
  50.                 return pos.dist;
  51.  
  52.             // bfs next
  53.             for (int i = 0; i < 8; i++)
  54.             {
  55.                 int r = pos.r + dx[i];
  56.                 int c = pos.c + dy[i];
  57.                 if (valid(r, c) && !visited[r][c])
  58.                     q.add(new Pos(r, c, pos.dist + 1));
  59.             }
  60.         }
  61.         return -1;
  62.     }
  63.  
  64.     private boolean valid(int r, int c)
  65.     {
  66.         return r >= 0 && r < n && c >= 0 && c < n;
  67.     }
  68.  
  69. }
  70.  
  71. class Pos
  72. {
  73.     int r, c, dist;
  74.  
  75.     public Pos(String str, int dist)
  76.     {
  77.         r = str.charAt(0) - 'a';
  78.         c = Integer.parseInt(str.charAt(1) + "") - 1;
  79.         this.dist = dist;
  80.     }
  81.  
  82.     public Pos(int r, int c, int dist)
  83.     {
  84.         this.r = r;
  85.         this.c = c;
  86.         this.dist = dist;
  87.     }
  88.    
  89.     public String toString()
  90.     {
  91.         return r + "," + c + " : " + dist;
  92.     }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement