Problem solution · C++

Maximum Number of Moves to Kill All Pawns

Maximum Number of Moves to Kill All Pawns: a C++ solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
90 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Maximum Number of Moves to Kill All Pawns, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 90 lines of C++ from the credited upstream file 3283.cpp.
  • The implementation visibly relies on sequence storage, hash lookup, work queue, cached states.
  • 11 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Number of Moves to Kill All Pawns · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int maxMoves(int kx, int ky, vector<vector<int>>& positions) {    const int n = positions.size();    positions.push_back({kx, ky});    unordered_map<int, int> hashedPositionToIndex;    // dist[i][j] := the minimum distance from positions[i] to positions[j]    vector<vector<int>> dist(n + 1, vector<int>(n + 1));     for (int i = 0; i < positions.size(); ++i) {      const int x = positions[i][0];      const int y = positions[i][1];      hashedPositionToIndex[hash(x, y)] = i;    }     for (int sourceIndex = 0; sourceIndex < n + 1; ++sourceIndex)      bfs(positions, sourceIndex, hashedPositionToIndex, dist);     const int maxMask = 1 << (n + 1);    // dp[i][mask][turn] := the maximum (Alice) or the minimum (Bob) cost to    // kill all pawns, where i is the current pawn, mask is the set of pawns    // that have been killed, and turn is the current player's turn (0 for Alice    // and 1 for Bob)    vector<vector<vector<int>>> dp(        n + 1, vector<vector<int>>(1 << (n + 1), vector<int>(2)));     for (int i = 0; i < n + 1; ++i)      for (int mask = 0; mask < maxMask - 1; ++mask)        dp[i][mask] = {-kMax, kMax};     for (int mask = maxMask - 2; mask >= 0; --mask)      for (int i = 0; i < n + 1; ++i)        for (int turn = 0; turn < 2; ++turn)          for (int j = 0; j < n; ++j) {            if (mask >> j & 1)              continue;            const int moves = dist[i][j] + dp[j][mask | 1 << j][1 - turn];            dp[i][mask][turn] = turn == 0 ? max(dp[i][mask][turn], moves)                                          : min(dp[i][mask][turn], moves);          }     // Returns the maximum cost to kill all pawns, i.e., the original positions    // array without the knight (kx, ky).    return dp[n][1 << n][0];  }  private:  static constexpr int kSize = 50;  static constexpr int kMax = 1'000'000;  static constexpr int kDirs[8][2] = {{1, 2},   {2, 1},   {2, -1}, {1, -2},                                      {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};   int hash(int x, int y) {    return x * kSize + y;  }   // Computes the distance between positions[sourceIndex] and other positions.  void bfs(const vector<vector<int>>& positions, int sourceIndex,           const unordered_map<int, int>& hashedPositionToIndex,           vector<vector<int>>& dist) {    const int sx = positions[sourceIndex][0];    const int sy = positions[sourceIndex][1];    queue<pair<int, int>> q{{{sx, sy}}};    vector<vector<bool>> seen(kSize, vector<bool>(kSize));    seen[sx][sy] = true;    int seenPositions = 0;     for (int step = 0; !q.empty() && seenPositions < positions.size(); ++step)      for (int sz = q.size(); sz > 0; --sz) {        const auto [i, j] = q.front();        q.pop();        if (const auto it = hashedPositionToIndex.find(hash(i, j));            it != end(hashedPositionToIndex)) {          dist[sourceIndex][it->second] = step;          ++seenPositions;        }        for (const auto& [dx, dy] : kDirs) {          const int x = i + dx;          const int y = j + dy;          if (x < 0 || x >= kSize || y < 0 || y >= kSize)            continue;          if (seen[x][y])            continue;          q.emplace(x, y);          seen[x][y] = true;        }      }  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗