๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ฏ | ๋ฐฑ์ค€/๐Ÿ™‚ | Silver

[Kotlin, S3] ๋ฐฑ์ค€ 15649๋ฒˆ N๊ณผ M(1)

by immgga 2024. 8. 13.

์ถœ์ฒ˜: unsplash.com

 

N๊ณผ M(1)(15649๋ฒˆ)

Silver 3

#๋ฐฑํŠธ๋ž˜ํ‚น

 

๋ฌธ์ œ ๋‚ด์šฉ

 

 

๋ฌธ์ œ ์ ‘๊ทผ

๋ฐฑํŠธ๋ž˜ํ‚น์„ ์ด์šฉํ•ด ํ•ด๊ฒฐ ๊ฐ€๋Šฅํ•˜๋‹ค.

์™„์ „ํƒ์ƒ‰์œผ๋กœ๋„ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ๋ฐฑํŠธ๋ž˜ํ‚น์„ ์“ฐ๋Š” ๊ฒŒ ๊ณต๋ถ€์— ๋„์›€์ด ๋  ๊ฒƒ ๊ฐ™๋‹ค.

 

1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ž์—ฐ์ˆ˜ ์ค‘ ์ค‘๋ณต ์—†์ด m๊ฐœ๋ฅผ ๊ณ ๋ฅด๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

๋ฐฑํŠธ๋ž˜ํ‚น์˜ ๊ฐœ๋…๋ถ€ํ„ฐ ๊ฐ„๋‹จํ•˜๊ฒŒ ์ด์•ผ๊ธฐํ•˜๊ฒ ๋‹ค.

 

๋ฐฑํŠธ๋ž˜ํ‚น์€ ์ผ์ž๋กœ ์ญ‰ ๋‚ด๋ ค๊ฐ€๋‹ค๊ฐ€ ์ •๋‹ต์ด ์•„๋‹˜์ด ํ™•์‹ค์‹œ๋˜๋ฉด ์ด์ „์œผ๋กœ ๋Œ์•„์™€์„œ ๋‹ค์‹œ ๋‹ค๋ฅธ ๊ฒฝ๋กœ๋กœ ๊ฒ€์ƒ‰์„ ์‹œ์ž‘ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

๊ฐ„๋‹จํ•˜๊ฒŒ ์‚ฌ์ง„์œผ๋กœ ์ง„ํ–‰ ๊ณผ์ •์„ ๋ด๋ณด์ž.

์‚ฌ์ง„ 1-1

 

์ฒ˜์Œ์—๋Š” 0 -> 1 -> 3์œผ๋กœ ์ด๋™ํ•˜๋ฉด์„œ ํƒ์ƒ‰ํ•œ๋‹ค. 3์— ๋„๋‹ฌํ•˜๋ฉด ๋” ๊นŠ๊ฒŒ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋ถ€๋ชจ ๋…ธ๋“œ๋กœ ๋‹ค์‹œ ์ด๋™ํ•ด์„œ ๋‹ค๋ฅธ ๊ฒฝ๋กœ๋กœ ์žฌํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค.

 

๋ถ€๋ชจ ๋…ธ๋“œ๋กœ ๋Œ์•„๊ฐ€๋Š” ๋ฐฉ๋ฒ•์€ ์ž์‹๊นŒ์ง€ dfs๋กœ ํŠน์ • ๊นŠ์ด๊นŒ์ง€ ๋“ค์–ด๊ฐ€๊ณ  ๋‚˜๋ฉด ์ €์žฅํ•˜๋ฉด์„œ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ์„ค์ •ํ•  ํ…๋ฐ ๋ฐ˜๋ณต์ด ๋๋‚˜๊ณ , ๋ถ€๋ชจ์˜ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ํ•ด์ œํ•˜๋Š” ๊ฒƒ์œผ๋กœ ๋ถ€๋ชจ์˜ ๋…ธ๋“œ๋ฅผ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ๋‹ค. ํ•˜์ง€๋งŒ ์ด์ „์— ๋“ค์–ด๊ฐ”๋˜ ๊ณณ์€ ์ด๋ฏธ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๊ฐ€ ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋“ค์–ด๊ฐ€์ง€ ๋ชปํ•˜๊ณ , ๋‹ค๋ฅธ ๊ฒฝ๋กœ๋กœ ๋“ค์–ด๊ฐ€๊ฒŒ ๋œ๋‹ค.

 

 

๋ฌธ์ œ ํ•ด๊ฒฐ ์ฝ”๋“œ

๋”๋ณด๊ธฐ
import java.io.BufferedReader
import java.io.InputStreamReader

private var res = arrayOf<Int>()
private var visited = booleanArrayOf()
private var num = 0
private var size = 0

private val sb = StringBuilder()

fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {
    val input = readLine().split(" ").map { it.toInt() }
    num = input.first()
    size = input.last()
    res = Array(size) { 0 }
    visited = BooleanArray(num)

    dfs(0)

    println(sb)
}

private fun dfs(depth: Int) {
    if (depth == size) {
        for (r in res) {
            sb.append("$r ")
        }
        sb.append("\n")
        return
    }

    for (i in 0 until num) {
        if (!visited[i]) {
            visited[i] = true
            res[depth] = i+1
            dfs(depth + 1)

            visited[i] = false
        }
    }
}

 

๋ฌธ์ œ ํ’€์ด

dfs๋กœ ๋ฐฑํŠธ๋ž˜ํ‚น์„ ์‹œ์ž‘ํ•œ๋‹ค.

dfs์—๋Š” depth๋ผ๋Š” ์–ผ๋งˆ๋‚˜ ๊นŠ์ด ๋“ค์–ด๊ฐ€๋Š”์ง€ ํ™•์ธํ•˜๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๋งŒ ๋ฐ›๋Š”๋‹ค.

depth๊ฐ€ ์ž…๋ ฅ๋ฐ›์€ size๋ž‘ ๊ฐ™์•„์ง€๋ฉด ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

 

๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•ด res์— ๋„ฃ์–ด์ค€๋‹ค.

๊ทธ๋ฆฌ๊ณ  ์žฌ๊ท€ ํ˜ธ์ถœ์„ ํ•ด์ค€๋‹ค.

์žฌ๊ท€ ํ˜ธ์ถœ์ด ๋๋‚œ ๋‹ค์Œ์—๋Š” ๋ถ€๋ชจ์˜ ๋ฐฉ๋ฌธ ์ฒดํฌ๋ฅผ ํ•ด์ œํ•œ๋‹ค.

 

 

๋ฌธ์ œ ํ•ด๊ฒฐ ๊ณผ์ •

๋ฐฑํŠธ๋ž˜ํ‚น์€ ์ฒ˜์Œ์ด๋ผ ์–ด๋ ต๋‹ค. ์™„์ „ํƒ์ƒ‰์œผ๋กœ๋„ ํ’€ ์ˆ˜ ์žˆ์–ด์„œ Silver 3์ธ ๋“ฏํ•˜๋‹ค. ๋ฐฑํŠธ๋ž˜ํ‚น ์—ฐ์Šต์šฉ ๋ฌธ์ œ์ด๋‹ค.

๊ฐ™์€ ์ด๋ฆ„์˜ ๋ฌธ์ œ๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ ์žˆ์–ด ๋ฐฑํŠธ๋ž˜ํ‚น ์—ฐ์Šต์—๋Š” ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.

728x90