Exemple #1
0
    def h(cls, state: TileBoard):
        manhattan_sum = 0

        # Populates Solved State
        solved = [[None for c in range(state.cols)] for r in range(state.rows)]
        index = 1
        for row in range(state.boardsize):
            for col in range(state.boardsize):
                if row == state.rows // 2 and col == state.cols // 2:
                    solved[row][col] = None
                else:
                    solved[row][col] = index
                    index += 1

        # Calculate Displacements
        for row in range(state.boardsize):
            for col in range(state.boardsize):
                item = state.get(row, col)
                # Find location for solved state
                for solved_row in range(len(solved)):
                    if item in solved[solved_row]:
                        # Adds manhattan distance to manhattan_sum
                        # If item is at [1, 2] in state and [0, 0] in solved then distance is 1 + 2 = 3
                        manhattan_sum += abs(solved_row - row) + abs(solved[solved_row].index(item) - col)
        return manhattan_sum
Exemple #2
0
 def h(cls, state: TileBoard):
     manhattan_distance = 0
     goal_state = list(state.goals[0])
     size = state.boardsize
     # calculate misplacement tiles
     # h = |x1 − x2| + |y1 − y2|
     # for index above board mod board_size will get cols
     # for index above board divide board_size will get rows
     for row in range(size):
         for col in range(size):
             # not count the blank for misplacement
             if state.get(row, col) is not None:
                 val_rc = state.get(row, col)
                 idx = goal_state.index(val_rc)
                 if idx > size - 1:
                     manhattan_distance += abs(idx // size - row) + abs(idx % size - col)
                 else:
                     manhattan_distance += row + abs(idx - col)
     return manhattan_distance
    def h(cls, state: TileBoard):
        manhattan_solution = 0

        solved = [[None for c in range(state.cols)] for r in range(state.rows)]
        index = 1
        for row in range(state.boardsize):
            for col in range(state.boardsize):
                if row == state.rows // 2 and col == state.cols // 2:
                    solved[row][col] = None
                else:
                    solved[row][col] = index
                    index += 1

        # Calculate distance to solution
        for row in range(state.boardsize):
            for col in range(state.boardsize):
                item = state.get(row, col)
                for solved_row in range(len(solved)):
                    manhattan_solution += abs(solved_row - row) + \
                        abs(solved[solved_row].index(item) - col)

        return manhattan_solution