Manhattan Distances of All Arrangements of Pieces - Problem

You are given three integers m, n, and k. There is a rectangular grid of size m × n containing k identical pieces.

Return the sum of Manhattan distances between every pair of pieces over all valid arrangements of pieces.

A valid arrangement is a placement of all k pieces on the grid with at most one piece per cell.

Since the answer may be very large, return it modulo 10^9 + 7.

The Manhattan Distance between two cells (x_i, y_i) and (x_j, y_j) is |x_i - x_j| + |y_i - y_j|.

Input & Output

Example 1 — Small Grid
$ Input: m = 1, n = 2, k = 2
Output: 1
💡 Note: Only one arrangement possible: both pieces at positions (0,0) and (0,1). Distance = |0-0| + |0-1| = 1.
Example 2 — Square Grid
$ Input: m = 2, n = 2, k = 2
Output: 8
💡 Note: Grid has 4 cells, C(4,2) = 6 arrangements. Sum of all pairwise distances across arrangements equals 8.
Example 3 — Single Piece
$ Input: m = 3, n = 3, k = 1
Output: 0
💡 Note: With only one piece, there are no pairs to calculate distance between, so sum is 0.

Constraints

  • 1 ≤ m, n ≤ 100
  • 1 ≤ k ≤ m × n
  • Answer fits in 32-bit integer after modulo

Visualization

Tap to expand
Manhattan Distances: All Arrangements SumInput: m=2, n=3, k=22×3 grid, place 2 piecesSample ArrangementsDistance = 1Distance = 2Mathematical FormulaFor each cell pair (A,B):distance × C(total-2, k-2)Sum over all pairsDivide by 2All C(6,2) = 15 arrangements contribute to final sumInstead of enumerating, use combinatorial counting:Distance 1 appears in X arrangements, distance 2 in Y arrangements, etc.Output: Sum of all distances modulo 10⁹+7
Understanding the Visualization
1
Input
Grid dimensions m×n and k pieces to place
2
Process
Calculate Manhattan distances for all arrangements
3
Output
Sum of all pairwise distances modulo 10^9+7
Key Takeaway
🎯 Key Insight: Use combinatorial mathematics to count distance contributions without generating all arrangements
Asked in
Google 25 Meta 18 Microsoft 15 Amazon 12
12.4K Views
Medium Frequency
~35 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen