4

Is there a mathematical formula one can use to compute the minimum number of knight moves to get between two points in a infinite 2D grid? I can figure it out using a breadth-first search, but is there a closed-form expression we can use instead?

Thanks!

Ahmed Ameen
  • 41
  • 1
  • 3
  • Is the grid finite or infinite? I guess for infinite grids, one can visualize the BFS tree starting at the origin, and try to come up with a formula describing that. But for a finite grid, the boundaries will probably cause lots of special cases. – MvG Oct 21 '13 at 10:04
  • we can assume the gird is infinite – Ahmed Ameen Oct 22 '13 at 22:00
  • 2
    I believe this is the answer you're looking for: http://stackoverflow.com/a/8778592/1729005 – axblount Oct 22 '13 at 22:05

1 Answers1

3

I dont think there is one formula that generates the minimum distands for all pairs of points.

But for some special points there are. Let A,B be points on a 2D - Grid with A = (0,0) and B = (x,y) and dist(x,y) the minimum number of knight moves.

First of all, the distance is symmetric:

dist(x,y) = dist(-x,y) = dist(x,-y) = dist(-x,-y) = dist(y,x)

  1. Case: 2x=y -> dist(x,2x) = x
  2. Case: x = 0
    • Subcase 1: y = 4k (k is a natural number)
      -> dist(x,y) = 2k
    • Subcase 2: y = 4k+1 or y = 4k+3
      -> dist(x,y) = 2k + 3
    • Subcase 3: y = 4k+2
      -> dist(x,y) = 2k + 2
  3. Case: x = y
    • Subcase 1: x = 3k (k is a natural number)
      -> dist(x,y) = 2k
    • Subcase 2: x = 3k+1
      -> dist(x,y) = 2k + 2
    • Subcase 3: y = 3k+2
      -> dist(x,y) = 2k + 4

If B (with 0 <= x <= y) fits in no case, you know at least
dist(x,y) <= dist(x-k,y-2k) + dist(k,2k) = dist(0,y-2k) + k
and
dist(x,y) <= dist(x-z,y-z) + dist(z,z) = dist(0,y-z) + dist(z,z)

EDIT: I have thought about it a little more. I think the following algorithm computs the minimum moves (Maple Code):

dist := proc(x,y)
  global d;
  local temp;

  if x < 0 then x:= -x; fi;
  if y < 0 then y:= -y; fi;
  if x > y then temp := x; x:= y; y:= temp; fi;

  if y = 2*x then return x; fi;
  if x = y then 
    if x mod 3 = 0 then return 2*(x/3); fi;
    if x mod 3 = 1 then return 2+2*(x-1)/3 fi;
    if x mod 3 = 1 then return 4+2*(x-2)/3 fi;
  fi;
  if x = 0 then
    if y mod 4 = 0 then return y/2; fi;
    if y mod 4 = 1 or y mod 4 = 3 then return 3+(y - (y mod 4))/2; fi;
    if y mod 4 = 2 then return 2+(y-2)/2; fi;
  fi;
  if y > 2*x then
    return dist(0,y-2*x) + dist(x,2*x);        
  else
    return dist(2*x-y,2*x-y) + dist(y-x,2*(y-x));
  fi;
end proc:

NOTE: this is only correct on a infinite 2D grid.

EDIT2: This (recursive) algorithm runs in O(1) (time and space) cause it has a constant number of O(1) operations and calls it self at most one more time.

EDIT3: I thought a littel further and I think this is also correkt on a finite 2D grid, if A or B are at least 1 row/column away from at least one border.

AbcAeffchen
  • 12,535
  • 15
  • 46
  • 62