Maps app~30 min2s · 256 MBtarget O(r c) time, O(r c) spacebfs
A city map is printed on a grid. Each cell holds the number of its district, from 0 to k - 1, and every number appears at least once. A cell with -1 is sea and belongs to no district.
The printer has two inks, ink 0 and ink 1. Two districts that share a border must get different inks, so that the border shows. Painting district d costs costs[d][0] with ink 0 and costs[d][1] with ink 1.
Write cheapest_inking(districts, costs).
districts[r][c] is the district of that cell, or -1 for sea.costs[d] is [cost_with_ink_0, cost_with_ink_1], and k = costs.length.-1 when no plan exists.Input: districts = [[0,0,1,1],[0,0,1,1],[2,2,3,3]], costs = [[3,5],[4,1],[2,6],[7,2]]
Output: 13Districts 0 and 3 touch only at a corner, so the touching pairs are 0-1, 0-2, 1-3 and 2-3: a ring of four. A search colours it from district 0 with ink 0, then prices the colouring and its swap.
| Colouring | District 0 | District 1 | District 2 | District 3 | Total |
|---|---|---|---|---|---|
| As found | ink 0: 3 | ink 1: 1 | ink 1: 6 | ink 0: 7 | 17 |
| Swapped | ink 1: 5 | ink 0: 4 | ink 0: 2 | ink 1: 2 | 13 |
The swapped colouring is cheaper, so the answer is 13.
Input: districts = [[0,1],[2,2]], costs = [[1,1],[1,1],[1,1]]
Output: -1Districts 0, 1 and 2 all touch each other, a ring of three. Two inks cannot colour it.
Input: districts = [[0,-1,1],[0,-1,1]], costs = [[5,3],[2,8]]
Output: 5The sea column splits the map into two islands that touch nothing. Each island takes its cheaper ink: 3 for district 0 and 2 for district 1.
1 ≤ rows, columns ≤ 3001 ≤ k ≤ 90,000, and every district number from 0 to k - 1 appears in the grid; sea is -10 ≤ costs[d][i] ≤ 1,000,000Trying both inks for each of up to 90,000 districts means 2^k plans, far beyond reach. In a group of touching districts, one district's ink decides all the others, so a group has only two plans. One search over the grid and its borders costs O(r c). Totals reach 90,000 × 10^6 = 9 × 10^10, which needs 64 bits.