๋ฌธ์
ํ์ด ์ธ์ด
Kotlin
์ฝ๋
import java.lang.Integer.min
import java.util.*
import kotlin.math.abs
import kotlin.system.exitProcess
lateinit var board: Array<Array<Int>>
lateinit var visited: Array<Int>
var min_value = Int.MAX_VALUE
var n = 0
fun main() = with(Scanner(System.`in`)) {
n = nextInt()
board = Array(n) { Array(n) { nextInt() } }
visited = Array(n) { 0 }
search(0, 0)
println(min_value)
}
fun search(index: Int, depth: Int) {
if (depth == n / 2) {
calculate()
return
}
for (i in index until n) {
if (visited[i] == 0) {
visited[i] = 1
search(i + 1, depth + 1)
visited[i] = 0
}
}
}
fun calculate() {
var start = 0
var link = 0
for (i in 0 until n - 1) {
for (j in i until n) {
if (visited[i] == 1 && visited[j] == 1) {
start += board[i][j]
start += board[j][i]
} else if (visited[i] == 0 && visited[j] == 0) {
link += board[i][j]
link += board[j][i]
}
}
}
val score = abs(start - link)
if (score == 0) {
println(score)
exitProcess(0)
}
min_value = min(score, min_value)
}
ํ์ด ๋ฐฉ๋ฒ
๊ฐ์ธ์ ์ผ๋ก ๋ฐฑํธ๋ํน
์ด๋ป๊ฒ ์ ์ฉํ ์ง๋ฅผ ๋ฐ๊ฒฌํ์ง ๋ชปํด์ ์์ ์์ฑํ ๊ณจ๋
๋ฌธ์ ๋ณด๋ค ์ด๋ ค์ ๋ค. ์ฐ์ 2๊ฐ์ ํ (์คํํธํ, ๋งํฌํ) ์ผ๋ก ๋๋์ด์ผ ํ๋ค. ๋ฐฉ๋ฌธ ์ง์ ์ ์คํํธํ
์ผ๋ก ๋๊ณ ๋ฐฉ๋ฌธํ์ง ์๋ ์ง์ ์ ๋งํฌํ
์ผ๋ก ๋๊ณ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ค.
1. 2๊ฐ์ ํ์ผ๋ก ๋๋๋ฏ๋ก depth == n / 2
์ธ ๊ฒฝ์ฐ์ ์ ์ ๊ณ์ฐ
fun search(index: Int, depth: Int) {
if (depth == n / 2) {
calculate()
return
}
for (i in index until n) {
if (visited[i] == 0) {
visited[i] = 1
search(i + 1, depth + 1)
visited[i] = 0
}
}
}
2. ๋ฐฉ๋ฌธํ ์ง์ ์ ์คํํธํ์ผ๋ก, ๋ฐฉ๋ฌธํ์ง ์์ ์ง์ ์ ๋งํฌํ์ผ๋ก ๋๊ณ ์ ์ ๊ณ์ฐ
for (i in 0 until n - 1) {
for (j in i until n) {
if (visited[i] == 1 && visited[j] == 1) {
start += board[i][j]
start += board[j][i]
} else if (visited[i] == 0 && visited[j] == 0) {
link += board[i][j]
link += board[j][i]
}
}
}
val score = abs(start - link)
min_value = min(score, min_value)
3. ์ ์์ ์ฐจ์ด๊ฐ 0์ด๋ฉด ์ต์๊ฐ์ด๋ฏ๋ก DFS๋ฅผ ์งํํ์ง ์๊ณ ์ข ๋ฃ
if (score == 0) {
println(score)
exitProcess(0)
}
๊ฒฐ๊ณผ
'โ๏ธ ์ฝํ ์ค๋น > Back Tracking' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑํธ๋ํน / Kotlin] BOJ 1759 - ์ํธ ๋ง๋ค๊ธฐ (0) | 2022.04.10 |
---|---|
[๋ฐฑํธ๋ํน / Kotlin] BOJ 1987 - ์ํ๋ฒณ (0) | 2022.04.10 |
[๋ฐฑํธ๋ํน / Kotlin] BOJ 14888 - ์ฐ์ฐ์ ๋ผ์๋ฃ๊ธฐ (0) | 2022.03.31 |
[๋ฐฑํธ๋ํน / Kotlin] BOJ 2580 - ์ค๋์ฟ (0) | 2022.03.30 |
[๋ฐฑํธ๋ํน / Kotlin] BOJ 9663 - N Queen (0) | 2022.03.29 |