2025-09-10 20:21:02 +09:00

83 lines
2.2 KiB
Swift

func combination(_ n: Int, _ r: Int) -> [[Int]] {
var resultComb: [[Int]] = []
var currentComb: [Int] = []
func backtracking(_ start: Int) {
if currentComb.count == r {
resultComb.append(currentComb)
return
}
for i in start...n {
currentComb.append(i)
backtracking(i + 1)
currentComb.removeLast()
}
}
backtracking(0)
return resultComb
}
if let input = readLine(),
let NM = input.split(separator: " ").compactMap({Int($0)}) as? [Int],
let N = NM.first, let M = NM.last
{
var house: [[Int]] = []
var chicken: [[Int]] = []
for i in 0..<N {
if let line = readLine(),
let row = line.split(separator: " ").compactMap({Int($0)}) as? [Int],
row.count == N
{
for j in 0..<N {
if row[j] == 1 {
house.append([i, j])
} else if row[j] == 2 {
chicken.append([i, j])
}
}
}
}
var Distance: [[Int]] = Array(repeating: Array(repeating: 0, count: chicken.count), count: house.count)
for i in 0..<house.count {
let r1: Int = house[i][0]; let c1: Int = house[i][1]
for j in 0..<chicken.count {
let r2 = chicken[j][0]; let c2 = chicken[j][1]
Distance[i][j] = abs(r1 - r2) + abs(c1 - c2)
}
}
var distanceMinSum: Int = 0
if M == chicken.count {
for i in 0..<house.count {
distanceMinSum += Distance[i].min() ?? 0
}
}
else {
let combList: [[Int]] = combination(chicken.count, chicken.count - M)
var minDistance = Int.max
for comb in combList {
var tempDistMin: Int = 0
var tempDist: [[Int]] = Distance
for i in 0..<house.count {
for j in comb {
tempDist[i][j] = Int.max
}
tempDistMin += tempDist[i].min() ?? 0
}
if minDistance > tempDistMin {
minDistance = tempDistMin
}
}
distanceMinSum = minDistance
}
print(distanceMinSum)
}