787. Sliding Puzzle
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the minimum number of moves to solve a 2x3 sliding puzzle. A move consists of swapping the empty square (0) with an adjacent tile. This problem can be modeled as finding the shortest path in an unweighted graph.
Solution
Sliding Puzzle in Python
import collections
class Solution:
def slidingPuzzle(self, board: list[list[int]]) -> int:
# The target state of the puzzle.
target = "123450"
# Flatten the 2x3 board into a single string.
start = "".join(str(num) for row in board for num in row)
if start == target:
return 0
# Pre-calculate the possible swaps for each position of the empty tile '0'.
# The indices are 0-5 for the flattened board.
neighbors = [
[1, 3], [0, 2, 4], [1, 5],
[0, 4], [1, 3, 5], [2, 4]
]
# BFS setup
q = collections.deque([start])
visited = {start}
moves = 0
while q:
# Process one level at a time
level_size = len(q)
for _ in range(level_size):
current = q.popleft()
# Find the position of the empty tile '0'.
zero_pos = current.find('0')
# Generate next states by swapping '0' with its neighbors.
for neighbor_pos in neighbors[zero_pos]:
temp_list = list(current)
temp_list[zero_pos], temp_list[neighbor_pos] = temp_list[neighbor_pos], temp_list[zero_pos]
next_state = "".join(temp_list)
if next_state == target:
return moves + 1
# If this state has not been visited, add it to the queue and visited set.
if next_state not in visited:
visited.add(next_state)
q.append(next_state)
moves += 1 # Increment moves after exploring a full level
# If the queue becomes empty and the target is not reached, it's impossible.
return -1
Sliding Puzzle in Java
class Solution {
public int slidingPuzzle(int[][] board) {
// The target state of the puzzle.
String target = "123450";
// Flatten the 2x3 board into a single string.
StringBuilder sb = new StringBuilder();
for (int[] row : board) {
for (int cell : row) {
sb.append(cell);
}
}
String start = sb.toString();
if (start.equals(target)) {
return 0;
}
// Pre-calculate the possible swaps for each position of the empty tile '0'.
// Indices are 0-5 for the flattened board.
int[][] neighbors = {
{1, 3}, {0, 2, 4}, {1, 5},
{0, 4}, {1, 3, 5}, {2, 4}
};
// BFS setup
Queue<String> q = new LinkedList<>();
Set<String> visited = new HashSet<>();
q.add(start);
visited.add(start);
int moves = 0;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
String current = q.poll();
// Find the position of the empty tile '0'.
int zeroPos = current.indexOf('0');
// Generate next states by swapping '0' with its neighbors.
for (int neighborPos : neighbors[zeroPos]) {
char[] currentChars = current.toCharArray();
char temp = currentChars[zeroPos];
currentChars[zeroPos] = currentChars[neighborPos];
currentChars[neighborPos] = temp;
String nextState = new String(currentChars);
if (nextState.equals(target)) {
return moves + 1;
}
// If this state has not been visited, add it to the queue and visited set.
if (!visited.contains(nextState)) {
visited.add(nextState);
q.add(nextState);
}
}
}
moves++;
}
// If the queue becomes empty and the target is not reached, it's impossible.
return -1;
}
}
Sliding Puzzle in C++
class Solution {
public:
int slidingPuzzle(vector<vector<int>>& board) {
// The target state of the puzzle.
string target = "123450";
string start = "";
// Flatten the 2x3 board into a single string.
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
start += to_string(board[i][j]);
}
}
if (start == target) {
return 0;
}
// Pre-calculate the possible swaps for each position of the empty tile '0'.
// The indices are 0,1,2 for the first row and 3,4,5 for the second row.
vector<vector<int>> neighbors = {
{1, 3}, {0, 2, 4}, {1, 5},
{0, 4}, {1, 3, 5}, {2, 4}
};
// BFS setup
queue<string> q;
unordered_set<string> visited;
q.push(start);
visited.insert(start);
int moves = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; ++i) {
string current = q.front();
q.pop();
// Find the position of the empty tile '0'.
int zero_pos = current.find('0');
// Generate next states by swapping '0' with its neighbors.
for (int neighbor_pos : neighbors[zero_pos]) {
string next_state = current;
swap(next_state[zero_pos], next_state[neighbor_pos]);
if (next_state == target) {
return moves + 1;
}
// If this state has not been visited, add it to the queue and visited set.
if (visited.find(next_state) == visited.end()) {
visited.insert(next_state);
q.push(next_state);
}
}
}
moves++;
}
// If the queue becomes empty and the target is not reached, it's impossible.
return -1;
}
};
Sliding Puzzle in TypeScript
function slidingPuzzle(board: number[][]): number {
// The target state of the puzzle.
const target = "123450";
// Flatten the 2x3 board into a single string.
const start = board.flat().join('');
if (start === target) {
return 0;
}
// Pre-calculate the possible swaps for each position of the empty tile '0'.
// The indices are 0-5 for the flattened board.
const neighbors: number[][] = [
[1, 3], [0, 2, 4], [1, 5],
[0, 4], [1, 3, 5], [2, 4]
];
// BFS setup
const q: string[] = [start];
const visited = new Set<string>([start]);
let moves = 0;
while (q.length > 0) {
const levelSize = q.length;
for (let i = 0; i < levelSize; i++) {
const current = q.shift()!; // Non-null assertion because q.length > 0
// Find the position of the empty tile '0'.
const zeroPos = current.indexOf('0');
// Generate next states by swapping '0' with its neighbors.
for (const neighborPos of neighbors[zeroPos]) {
const currentChars = current.split('');
// Swap characters
[currentChars[zeroPos], currentChars[neighborPos]] = [currentChars[neighborPos], currentChars[zeroPos]];
const nextState = currentChars.join('');
if (nextState === target) {
return moves + 1;
}
// If this state has not been visited, add it to the queue and visited set.
if (!visited.has(nextState)) {
visited.add(nextState);
q.push(nextState);
}
}
}
moves++;
}
// If the queue becomes empty and the target is not reached, it's impossible.
return -1;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.