Sponsored
Sponsored
Time Complexity: O(1) - There are a constant number of states (720) due to permutation limits.
Space Complexity: O(1) - As with time, space usage peaks at 720 given state permutations.
1from collections import deque
2
3def sliding_puzzle(board):
4 start = ''.join(str(num) for row in board for num in row)
5 target = '123450'
6 neighbors = {
7 0: [1, 3],
8 1: [0, 2, 4],
9 2: [1, 5],
10 3: [0, 4],
11 4: [3, 1, 5],
12 5: [2, 4]
13 }
14 queue = deque([(start, start.index('0'), 0)]) # (board_str, zero_index, depth)
15 visited = {start}
16 while queue:
17 board_str, zero_index, depth = queue.popleft()
18 if board_str == target:
19 return depth
20 for adj in neighbors[zero_index]:
21 new_board = list(board_str)
22 new_board[zero_index], new_board[adj] = new_board[adj], new_board[zero_index]
23 new_board_str = ''.join(new_board)
24 if new_board_str not in visited:
25 visited.add(new_board_str)
26 queue.append((new_board_str, adj, depth + 1))
27 return -1This Python code uses a BFS approach to solve the sliding puzzle. We convert the board into a string and use a map to determine swap positions for '0'. Initially, each configuration is enqueued with its depth. The goal is to find the shortest path to the solved state.
Time Complexity: O((6! = 720) log(720))
Space Complexity: O(720), based on the number of states handled.
1import java.util.*;
2
3public
This Java code implements the A* search algorithm to tackle the sliding puzzle. Nodes are compared based on the cost estimation which combines depth and heuristic calculations. Using Manhattan distance as a heuristic ensures the solution is efficiently discovered through optimal path estimation.