Sliding Puzzle: a hard LeetCode problem

Problem is here: https://leetcode.com/problems/sliding-puzzle/description/

On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.
A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
Examples:
Input: board = [[1,2,3],[4,0,5]]
Output: 1
Explanation: Swap the 0 and the 5 in one move.
Input: board = [[1,2,3],[5,4,0]]
Output: -1
Explanation: No number of moves will make the board solved.
Input: board = [[4,1,2],[5,0,3]]
Output: 5
Explanation: 5 is the smallest number of moves that solves the board.
An example path:
After move 0: [[4,1,2],[5,0,3]]
After move 1: [[4,1,2],[0,5,3]]
After move 2: [[0,1,2],[4,5,3]]
After move 3: [[1,0,2],[4,5,3]]
After move 4: [[1,2,0],[4,5,3]]
After move 5: [[1,2,3],[4,5,0]]
Input: board = [[3,2,4],[1,5,0]]
Output: 14

The good thing about this problem is the small input: we're dealing with a matrix with 6 cells only. Since we're looking for the least number of moves to go from one state (beginning state) to another state (the end state), one approach should be coming to mind: breadth-first-search, or BFS.
To implement a BFS here we'll need few tools:

A) A class that will encapsulate the elements to be enqueued. This class will have the config, position of the empty cell, and number of steps to get to this state
B) A Hashtable to keep track of the visited states
C) A key to be used in the Hashtable. In this case we'll flatten the 3x2 board into one dimension
D) A function to check whether we've arrived at the end state
E) A function to attempt to move from one state to another

All that together, and you have yourself a solution. Cheers, Marcelo.

public class Solution
{
public int SlidingPuzzle(int[,] board)
{
int[] config = new int[6];
int zeroIndex = 0;

int index = 0;
for (int c = 0; c < board.GetLength(0); c++)
{
for (int r = 0; r < board.GetLength(1); r++)
{
config[index] = board[c, r];
if (board[c, r] == 0) zeroIndex = index;
index++;
}
}

int retVal = 0;

Puzzle puzzle = new Puzzle(config, zeroIndex, 0);
string key = Key(puzzle);

Hashtable configSeen = new Hashtable();
configSeen.Add(key, true);
Queue queue = new Queue();
queue.Enqueue(puzzle);
bool found = false;

while (queue.Count > 0)
{
Puzzle p = (Puzzle)queue.Dequeue();

if (IsFinalConfig(p))
{
found = true;
retVal = p.steps;
break;
}

switch (p.zeroPosition)
{
case 0:
AttemptEnqueue(p, 0, 1, configSeen, queue);
AttemptEnqueue(p, 0, 3, configSeen, queue);
break;
case 1:
AttemptEnqueue(p, 1, 0, configSeen, queue);
AttemptEnqueue(p, 1, 2, configSeen, queue);
AttemptEnqueue(p, 1, 4, configSeen, queue);
break;
case 2:
AttemptEnqueue(p, 2, 1, configSeen, queue);
AttemptEnqueue(p, 2, 5, configSeen, queue);
break;
case 3:
AttemptEnqueue(p, 3, 0, configSeen, queue);
AttemptEnqueue(p, 3, 4, configSeen, queue);
break;
case 4:
AttemptEnqueue(p, 4, 3, configSeen, queue);
AttemptEnqueue(p, 4, 5, configSeen, queue);
AttemptEnqueue(p, 4, 1, configSeen, queue);
break;
case 5:
AttemptEnqueue(p, 5, 4, configSeen, queue);
AttemptEnqueue(p, 5, 2, configSeen, queue);
break;
}
}

return found ? retVal : -1;
}

private void AttemptEnqueue(Puzzle p, int i, int j, Hashtable configSeen, Queue queue)
{
Swap(p, i, j);
string key = Key(p);
if (!configSeen.ContainsKey(key))
{
configSeen.Add(key, true);
Puzzle np = new Puzzle(p.config, j, p.steps + 1);
queue.Enqueue(np);
}
Swap(p, j, i);
}

private void Swap(Puzzle p, int i, int j)
{
int temp = p.config[i];
p.config[i] = p.config[j];
p.config[j] = temp;
}

private string Key(Puzzle p)
{
string key = "";
for (int i = 0; i < p.config.Length; i++)
{
key += p.config[i].ToString();
}
return key;
}

private bool IsFinalConfig(Puzzle puzzle)
{
for (int i = 0; i < puzzle.config.Length - 1; i++)
{
if (puzzle.config[i] != i + 1) return false;
}
return puzzle.config[puzzle.config.Length - 1] == 0;
}
}

public class Puzzle
{
public int[] config = null;
public int zeroPosition = 0;
public int steps = 0;

public Puzzle(int[] config, int zeroPosition, int steps)
{
this.config = (int[])config.Clone();
this.zeroPosition = zeroPosition;
this.steps = steps;
}
}


Comments

  1. what a fun problem!

    class Solution {
    private:
    const string TARGET = "123450";
    const array MOVES {-3, -1, 1, 3};
    public:
    int slidingPuzzle(vector>& board) {
    stringstream stream;
    for (int row = 0; row < board.size(); ++row) {
    copy(board[row].cbegin(), board[row].cend(), ostream_iterator(stream, ""));
    }
    string state = stream.str();
    queue q, next_q;
    q.push(state);
    unordered_set seen;
    for (int level = 0; !q.empty(); ) {
    string& current = q.front(); q.pop();
    if (current == TARGET) return level;
    int empty_pos = current.find("0");
    for (int move : MOVES) {
    int next_pos = empty_pos + move;
    if (next_pos < 0 || next_pos > 5 || empty_pos == 3 && next_pos == 2 || empty_pos == 2 && next_pos == 3) continue;
    string next_state = current;
    swap(next_state[empty_pos], next_state[next_pos]); // perform the move
    const auto& res = seen.insert(next_state);
    if (res.second) next_q.emplace(next_state); // new state
    }
    if (q.empty() && !next_q.empty()) {
    level += 1;
    swap(q, next_q);
    }
    }
    return -1;
    }
    };

    Reply Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...