Manhattan distance algorithm for any goal state 8-puzzle

roki

New Member
So, I have to solve the 8 puzzle problem, I choosed A* algorithm with manhattan distance as a heuristic. This is the function that computes the manhattan distance:\[code\]private static int md(int[][] tiles) { int manhattanDistanceSum = 0; for (int x = 0; x < 3; x++) for (int y = 0; y < 3; y++) { int value = http://stackoverflow.com/questions/15596341/tiles[x][y]; if (value != 0) { int targetX = (value - 1) / 3; int targetY = (value - 1) % 3; int dx = x - targetX; int dy = y - targetY; manhattanDistanceSum += Math.abs(dx) + Math.abs(dy); } } return manhattanDistanceSum;}\[/code\]The problem is that this gives me a good result only if the goal state is:123456780How should I modify it to work with any goal state?
 
Back
Top