Member-only story
Go solution to LeetCode 1007 Minimum Domino Rotation for Equal Row
In this Leetcode problem, we are given a list of dominos, each domino has 2 values between 1 and 6 (I think usually dominos can also have 0 has a value, but it doesn’t really matter here), a top value and a bottom value. You want all the top values or all the bottom values to be equal. To do that you can flip the domino, which exchange its top and bottom value. The question is, how to do that in the minimum possible number of moves? If it is not possible, return -1.
To resolve this problem, we first can notice that it is only possible to resolve the problem if a number appear at least once on each domino. This is why I introduced the method count
which return the number of dominos on which each of the possible values is present:
func count(A []int, B []int) [7]int {
var count [7]int
for i, v := range A {
count[v]++
if (A[i] != B[i]) {
count[B[i]]++
}
}
return count
}
If count[i]
matches with len(A)
, then it is possible to resolve the problem for the value i
.
Then I introduced the method cost
, it calculates the minimum cost to align all top or bottom values to match i
. To do that, it calculates the cost of aligning them at the bottom (costB
), and the cost of aligning them on top (costA
), then it returns…