Sliding Puzzle

Introduction

Sliding puzzle and its variations are pretty popular among puzzle games. Typically, the game is played on a 3 x 3 board or a 4 x 4 board with one empty tile to shift. You can check it out here if you haven't played before.

Sliding Puzzle (LC.773)

Given the puzzle board 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.

Example

Input: board = [[1,2,3],[4,0,5]]
Output: 1

Input: board = [[1,2,3],[5,4,0]]
Output: -1

Input: board = [[4,1,2],[5,0,3]]
Output: 5

Level BFS

idea

Code

Solvability

Proof tbd

This check improves the runtime from 228ms to 84ms.

We can frame this question as a shortest path finding in a weighted graph.

  • Shortest path - Dijkstra's algorithm

  • Weight

    • Actual cost - Number of steps

    • Heuristic - Manhattan distance (admissible)

      • Estimate the cost from the current node to the target node

      • Best lower bound to the actual cost

A very helpful visualization can be found here.

Code

This improves the runtime from 84ms to 52ms.

The graph size is pretty small for this question because of the board size. The performance improvement should be more noticeable if the board size is 4 x 4 or larger.

Analysis

The search graph is a lot smaller with a* than regular BFS.

For example with this board [[4,1,2],[5,0,3]]

O(whole graph) to O(1 / 4 of the graph?)

Reading

Last updated