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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code