1

I'm calculating Manhattan's distance for a N-Puzzle game. I've searched in all sites, but the proposed solution isn't good.

I'm trying this with this code:

def calculateManhattanDistance(matrix):
size  = len(matrix)
manhattanDistanceSum = 0
for i in range(size):
    for j in range(size):
        value = matrix[i][j]
        if(value != 0):
            targetX = (value)/size
            targetY = (value)%size
            dx = i-targetX
            dy = j-targetY
            manhattanDistanceSum = manhattanDistanceSum + abs(dx)+ abs(dy)

The matrix'goal is:

0 1 2
3 4 5
6 7 8

If I try calculate the distance in the next matrix (the same to the goal):

0 1 2
3 4 5
6 7 8

The proposed solution is 3 :S But It must be 0

I'm using this page to calculate it: Manhattan distance but the solution isn't good for me.

Sorry for my regular english guys!

Community
  • 1
  • 1
kylehide65
  • 13
  • 4
  • 2
    `calculateManhattanDistance([[0,1,2],[3,4,5],[6,7,8]])` returns 0 for me (adding `return manhattanDistanceSum` to the end of your code). Exactly what input are you giving? – Greg Jul 13 '16 at 18:28
  • I cannot reproduce it as well, it returns 0. – Patrick Trentin Jul 15 '16 at 16:57

0 Answers0