20250910 baekjoon
This commit is contained in:
parent
7b38665087
commit
8e2fcb241d
82
code_study/Baekjoon/swift/15686.swift
Normal file
82
code_study/Baekjoon/swift/15686.swift
Normal file
@ -0,0 +1,82 @@
|
||||
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)
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user