๋ฌธ์
ํ์ด ์ธ์ด
Kotlin
์ฝ๋
import java.util.*
var l = 0
var c = 0
lateinit var array: Array<String>
lateinit var sortedArray: Array<String>
lateinit var visited: Array<Int>
var stringBuilder = StringBuilder()
fun main() = with(Scanner(System.`in`)) {
l = nextInt()
c = nextInt()
array = Array(c) { next() }
sortedArray = array.sortedArray()
visited = Array(c) { 0 }
dfs(0, 0)
println(stringBuilder)
}
fun dfs(index: Int, depth: Int) {
if (depth == l) {
var consonants = 0 // ์ต์ 2๊ฐ์ ์์
var vowels = 0 // ์ต์ 1๊ฐ์ ๋ชจ์
for (i in 0 until c) {
if (visited[i] == 1) {
if (check(sortedArray[i])) vowels++
else consonants++
}
}
if (consonants >= 2 && vowels >= 1) {
for (i in 0 until c) {
if (visited[i] == 1) stringBuilder.append(sortedArray[i])
}
stringBuilder.append("\n")
}
return
}
for (i in index until c) {
if (visited[i] == 0) {
visited[i] = 1
dfs(i, depth + 1)
visited[i] = 0
}
}
return
}
fun check(e: String): Boolean {
return e == "a" || e == "e" || e == "i" || e == "o" || e == "u"
}
ํ์ด ๋ฐฉ๋ฒ
์ค๋ฆ์ฐจ์
์ผ๋ก ์ ๋ ฌ๋ ๋ฌธ์์ด์์ ์์, ๋ชจ์์ ๊ฐ์๋ฅผ ํ์ธํ์ฌ ์ถ๋ ฅํ๋ ๋ฐฑํธ๋ํน
๋ฌธ์ ์ด๋ค.
1. ๋ฌธ์ ์์ ์ฌ์ ์์ด๋ผ๊ณ ์๋ ค์คฌ์ผ๋ฏ๋ก ์ฃผ์ด์ง ๋ฌธ์์ด์ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ
array = Array(c) { next() }
sortedArray = array.sortedArray()
2. DFS ๋ฅผ ์งํํ๊ณ ๋ฌธ์์ด์ด ์์ฑ๋๋ฉด ์์, ๋ชจ์์ ๊ฐ์๋ฅผ ํ์ธ
fun dfs(index: Int, depth: Int) {
if (depth == l) {
var consonants = 0 // ์ต์ 2๊ฐ์ ์์
var vowels = 0 // ์ต์ 1๊ฐ์ ๋ชจ์
for (i in 0 until c) {
if (visited[i] == 1) {
if (check(sortedArray[i])) vowels++
else consonants++
}
}
if (consonants >= 2 && vowels >= 1) {
for (i in 0 until c) {
if (visited[i] == 1) stringBuilder.append(sortedArray[i])
}
stringBuilder.append("\n")
}
return
}
for (i in index until c) {
if (visited[i] == 0) {
visited[i] = 1
dfs(i, depth + 1)
visited[i] = 0
}
}
return
}
fun check(e: String): Boolean {
return e == "a" || e == "e" || e == "i" || e == "o" || e == "u"
}
๊ฒฐ๊ณผ
'โ๏ธ ์ฝํ ์ค๋น > Back Tracking' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑํธ๋ํน / Kotlin] BOJ 14889 - ์คํํธ์ ๋งํฌ (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 |