If I understand correctly the problem:
- Difference between X positions of A and B : dX = Math.abs(ax - bx)
- Difference between Y positions of A and B : dY = Math.abs(ay - by)
- The shortest distance is : dX + dY
The problem with the shortest path is you can have different ways which uses the number of moves shortest distance. But you can code a preference in this move, for example, if you have to go from 0 to 24, the shortest distance is 3 and you have 3 shortest possible ways:
- [0,11,22,23]
- [0,1,12,23]
- [0,11,12,23]
I suppose you want to use the third possibility?
For that, compare dX and dY and move in the greater dimension, if dX > dY, move X, if dY > dX, moveY
Update : try this
public static int[] shortestPath(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
int[] path = new int[Math.abs(ax - bx) + Math.abs(ay - by) + 1];
for (int i = 0; i < path.length; i++)
path[i] = a = i == 0 ? a : getAdjacentInDirectionOf(x, a, b);
return path;
}
public static int getAdjacentInDirectionOf(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
int dx = Math.abs(ax - bx), dy = Math.abs(ay - by);
if (dx >= dy) return (int) (ax + Math.signum(bx - ax) + ay * x);
else return (int) (ax + (ay + Math.signum(by - ay)) * x);
}
Update : replace shortestPath() method from previous by this one to avoid first case
public static int[] shortestPath(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
int[] path = new int[Math.abs(ax - bx) + Math.abs(ay - by)];
for (int i = 0; i < path.length; i++)
path[i] = a = getAdjacentInDirectionOf(x, a, b);
return path;
}