import math


def num_tiles_not_in_position(state):
    """
    Calculates and returns the number of tiles which are not in their
    final positions.
    """
    n = len(state)
    total = 0
    for row in state:
        for tile in row:
            try:
                y = int(math.floor(float(tile)/n - (float(1)/n)))
                x = (tile - 1) % n
            except ValueError: #blank tile
                continue
            if row.index(tile) - x != 0 or state.index(row) - y != 0:
               total += 1
    return total