Sunday 15 March 2015

Nagarro:Minimum no of counts from the knight to reach the king?

Question. A chessboard was given to us. Where in there was a Knight and King was placed on certain positions. Our aim is to reach the king from the knight in minimum no of counts.As we know, knight can either move 2 steps vertical/horizontal and 1 step horizontal/vertical. same goes here as well. Proper image of the chess board was given in the question paper, and all the positions(max 8) were given that knight can take in the first step.

Solution:


package dailyPuzzle;
public class HorseMinStep {

  static int find(int x, int y) {

   if (x == 0 && y == 0)
   return 0;
  if (x == 0 && y == 1 || x == 1 && y == 0)
   return 3;
  if (x == 1 && y == 1)
   return 2;

   if ((x == 0 || y == 0) && (x == 3) || (y == 3))
   return 3;

   if (x == 2 && y == 2)
   return 4;
  if (x == 1 && y == 2 || x == 2 && y == 1)
   return 1;

   if (x > y) {
   return find(x - 2, y - 1) + 1;
  } else {
   return find(x - 1, y - 2) + 1;
  }

  }

  static int mod(int x, int y) {
  if (x > y)
   return x - y;
  return y - x;
 }

  public static void main(String[] args) {
  int hx = 0, hy = 0;
  int kx = 7, ky = 7;
  int x = mod(hx, kx);
  int y = mod(hy, ky);
  System.out.println(find(x, y));

  }

}
OUTPUT
6