Approach
Breadth-first search
For Sliding Puzzle, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 48 lines of C++ from the credited upstream file 773.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int slidingPuzzle(vector<vector<int>>& board) {4 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};5 constexpr int m = 2;6 constexpr int n = 3;7 constexpr char goal[] = "123450";8 string start;9 10 11 for (int i = 0; i < m; ++i)12 for (int j = 0; j < n; ++j)13 start += '0' + board[i][j];14 15 if (start == goal)16 return 0;17 18 queue<string> q{{start}};19 unordered_set<string> seen{start};20 21 for (int step = 1; !q.empty(); ++step)22 for (int sz = q.size(); sz > 0; --sz) {23 string s = q.front();24 q.pop();25 const int zeroIndex = s.find('0');26 const int i = zeroIndex / n;27 const int j = zeroIndex % n;28 for (const auto& [dx, dy] : kDirs) {29 const int x = i + dx;30 const int y = j + dy;31 if (x < 0 || x == m || y < 0 || y == n)32 continue;33 const int swappedIndex = x * n + y;34 swap(s[zeroIndex], s[swappedIndex]);35 if (s == goal)36 return step;37 if (!seen.contains(s)) {38 q.push(s);39 seen.insert(s);40 }41 swap(s[zeroIndex], s[swappedIndex]);42 }43 }44 45 return -1;46 }47};48