Chinese Postman or Route Inspection
Pattern: BFS and DFS
A route that walks every street and returns home costs the total weight, plus the cheapest way to make every vertex's degree even: pair up the odd-degree vertices and walk the shortest path between each pair a second time. Find all-pairs distances with Floyd-Warshall and the best pairing with a bitmask DP.
The problem
Given a connected undirected weighted graph, return the length of the shortest closed walk that uses every edge at least
once. Edges are [u, v, weight].
Think first
- When is the answer just the total weight?
- What must be added otherwise?
- How do you choose which odd vertices to join?
Hints
Brute force, and why it fails
Try every set of repeated edges: exponential in E.
The key insight
Odd vertices come in pairs, and the cheapest fix is a minimum-weight pairing on shortest-path distances.
Dry run
| total | 15 |
|---|---|
| odd | 1 2 |
Edges 0-1 (1), 0-2 (2), 1-2 (3), 2-3 (4), 1-3 (5). Total 15. Degrees: 0: 2, 1: 3, 2: 3, 3: 2.
The plan
total = sum of weights; d = Floyd-Warshall
odd = odd-degree vertices
best[mask]: pair the first unpaired odd vertex with each other one
return total + best[all]
Complexity
- Time
O(V³ + 2^k × k)- Space
O(V² + 2^k)
k is the number of odd vertices.
Edge cases
- All degrees even: the total weight.
- A single edge: twice its weight.
- Parallel paths.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int chinesePostman(int n, int[][] edges) {
final int INF = Integer.MAX_VALUE / 4;
int[][] d = new int[n][n];
for (int[] row : d) Arrays.fill(row, INF);
for (int i = 0; i < n; i++) d[i][i] = 0;
int[] degree = new int[n];
int total = 0;
for (int[] e : edges) {
d[e[0]][e[1]] = d[e[1]][e[0]] = Math.min(d[e[0]][e[1]], e[2]);
degree[e[0]]++;
degree[e[1]]++;
total += e[2]; // every street is walked at least once
}
for (int k = 0; k < n; k++) // shortest distances between all pairs
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
List<Integer> odd = new ArrayList<>();
for (int i = 0; i < n; i++) if (degree[i] % 2 == 1) odd.add(i);
int m = odd.size();
int[] best = new int[1 << m]; // best[mask]: cheapest way to pair up the odd vertices in mask
Arrays.fill(best, INF);
best[0] = 0;
for (int mask = 0; mask < (1 << m); mask++) {
if (best[mask] == INF || Integer.bitCount(mask) % 2 == 1) continue;
int a = 0;
while (a < m && (mask >> a & 1) == 1) a++; // the first unpaired odd vertex
if (a == m) continue;
for (int b = a + 1; b < m; b++) if ((mask >> b & 1) == 0) {
int next = mask | (1 << a) | (1 << b);
best[next] = Math.min(best[next], best[mask] + d[odd.get(a)][odd.get(b)]); // walk a to b twice
}
}
return total + best[(1 << m) - 1];
}
}C++
class Solution {
public:
int chinesePostman(int n, vector<vector<int>>& edges) {
const int INF = INT_MAX / 4;
vector<vector<int>> d(n, vector<int>(n, INF));
for (int i = 0; i < n; i++) d[i][i] = 0;
vector<int> degree(n, 0);
int total = 0;
for (const vector<int>& e : edges) {
d[e[0]][e[1]] = d[e[1]][e[0]] = min(d[e[0]][e[1]], e[2]);
degree[e[0]]++;
degree[e[1]]++;
total += e[2]; // every street is walked at least once
}
for (int k = 0; k < n; k++) // shortest distances between all pairs
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
vector<int> odd;
for (int i = 0; i < n; i++) if (degree[i] % 2 == 1) odd.push_back(i);
int m = static_cast<int>(odd.size());
vector<int> best(1 << m, INF); // best[mask]: cheapest way to pair up the odd vertices in mask
best[0] = 0;
for (int mask = 0; mask < (1 << m); mask++) {
if (best[mask] == INF || __builtin_popcount(mask) % 2 == 1) continue;
int a = 0;
while (a < m && (mask >> a & 1)) a++; // the first unpaired odd vertex
if (a == m) continue;
for (int b = a + 1; b < m; b++) if (!(mask >> b & 1)) {
int next = mask | (1 << a) | (1 << b);
best[next] = min(best[next], best[mask] + d[odd[a]][odd[b]]); // walk a to b twice
}
}
return total + best[(1 << m) - 1];
}
};Python
class Solution:
def chinesePostman(self, n: int, edges: list[list[int]]) -> int:
INF = float("inf")
d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
degree, total = [0] * n, 0
for u, v, w in edges:
d[u][v] = d[v][u] = min(d[u][v], w)
degree[u] += 1
degree[v] += 1
total += w # every street is walked at least once
for k in range(n): # shortest distances between all pairs
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
odd = [i for i in range(n) if degree[i] % 2]
m = len(odd)
best = [INF] * (1 << m) # best[mask]: cheapest way to pair up the odd vertices in mask
best[0] = 0
for mask in range(1 << m):
if best[mask] == INF:
continue
a = next((i for i in range(m) if not mask >> i & 1), m) # the first unpaired odd vertex
for b in range(a + 1, m):
if not mask >> b & 1:
nxt = mask | 1 << a | 1 << b
best[nxt] = min(best[nxt], best[mask] + d[odd[a]][odd[b]]) # walk a to b twice
return total + best[-1]Common mistakes
- Pairing odd vertices greedily.
- Using edge weights instead of shortest distances between odd vertices.