예제 #1
0
 def random_restart(self):
     configuration = [['#' for _ in range(n)] for _ in range(n)]
     positions = []
     i = 0
     while i < n:
         x, y = randint(0, n - 1), randint(0, n - 1)
         if (x, y) not in positions:
             positions.append((x, y))
             i += 1
     for i, j in positions:
         configuration[i][j] = 'Q'
     board = ChessboardState(configuration)
     while any(board.__eq__(e) for e in self.prev_expanded_states):
         configuration = [['#' for _ in range(n)] for _ in range(n)]
         positions.clear()
         i = 0
         while i < n:
             x, y = randint(0, n - 1), randint(0, n - 1)
             if (x, y) not in positions:
                 positions.append((x, y))
                 i += 1
         for i, j in positions:
             configuration[i][j] = 'Q'
         board = ChessboardState(configuration)
     return ChessboardStateNode(board)
예제 #2
0
 def solve(self, initial_chessboard_state):
     # Structure: each column should contain only one queen
     prev_expanded = []
     start_time = time.time()
     current_state, positions = self.get_chessboard_and_positions(
         initial_chessboard_state)
     while True:
         print("Current state #attacks =",
               current_state.get_attacking_count())
         current_state.print_chessboard()
         last_cost = current_state.get_attacking_count()
         if last_cost == 0:
             self.final_sol = current_state
             break
         positions = self.heuristic_move(positions)
         current_state = ChessboardState(queen_positions=positions)
         # while any(current_state.__eq__(x) for x in prev_expanded):
         #     positions = self.heuristic_move(positions)
         #     current_state = ChessboardState(queen_positions=positions)
         self.expanded_count += 1
         prev_expanded.append(current_state)
         if last_cost == current_state.get_attacking_count(
         ):  # local optima
             print("--- Local Optima ---")
             positions = self.random_move(positions)
             current_state = ChessboardState(queen_positions=positions)
             while any(current_state.__eq__(x) for x in prev_expanded):
                 positions = self.random_move(positions)
                 current_state = ChessboardState(queen_positions=positions)
             self.expanded_count += 1
             prev_expanded.append(current_state)
             last_cost = current_state.get_attacking_count()
         else:
             last_cost = current_state.get_attacking_count()
         self.steps_count += 1
     end_time = time.time()
     self.execution_time = end_time - start_time
     return self.final_sol