Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 15654๋ฒˆ - N๊ณผ M (5) (DFS๋กœ ํ’€๊ธฐ!)

๊ฐ์ž ๐Ÿฅ” 2022. 5. 4. 14:44
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ๋งํฌ

https://www.acmicpc.net/problem/15654

 

15654๋ฒˆ: N๊ณผ M (5)

N๊ฐœ์˜ ์ž์—ฐ์ˆ˜์™€ ์ž์—ฐ์ˆ˜ M์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์•„๋ž˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๊ธธ์ด๊ฐ€ M์ธ ์ˆ˜์—ด์„ ๋ชจ๋‘ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. N๊ฐœ์˜ ์ž์—ฐ์ˆ˜๋Š” ๋ชจ๋‘ ๋‹ค๋ฅธ ์ˆ˜์ด๋‹ค. N๊ฐœ์˜ ์ž์—ฐ์ˆ˜ ์ค‘์—์„œ M๊ฐœ๋ฅผ ๊ณ ๋ฅธ ์ˆ˜์—ด

www.acmicpc.net

 

๋ฌธ์ œํ’€์ด

  • ์ง€๋‚œ๋ฒˆ์— ํŒ€์› ํ•œ๋ถ„์ด ๋ง์”€ํ•ด์ฃผ์…จ๋˜ ๊ฟ€ํŒ์ด ์ƒ๊ฐ๋‚ฌ๋‹ค.
  • ์ถœ๋ ฅ๋˜๋Š” ์ˆœ์—ด์—์„œ, [ 1 1 ] [ 2 2 ] ์™€ ๊ฐ™์ด ์ค‘๋ณต๋˜๋Š” ๊ฐ’์ด ์•ˆ๋“ค์–ด์žˆ์ง€ ์•Š์€๊ฐ€? ๊ทธ๋ ‡๋‹ค๋ฉด visited ์ฒดํฌ๋ฅผ ํ•œ๋‹ค๋Š” ๋œป์ด๋‹ค!
  • ์ด ๋ง์„ ๊ธฐ์–ตํ•˜๋ฉด์„œ ์ฐจ๊ทผ์ฐจ๊ทผ dfs๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค.
  • dfs๋กœ ๊ตฌํ˜„ํ•œ ์ด์œ ๋Š”? ์ˆœ์—ด์— ๋‹ด๊ธฐ ์œ„ํ•ด์„œ ๋ชจ๋“  ์ˆ˜๋ฅผ ํƒ์ƒ‰ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค!

๋ฆฌ์ŠคํŠธ๋กœ ๋‹ด์€ ๊ฒƒ์„ ์ถœ๋ ฅํ•˜๋Š” ๊ฒƒ์ด ์ •๋ง ์–ด๋ ค์› ๋‹ค.  ํŒ€์›๋“ค์˜ ์ฝ”๋“œ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ์‹์„ ์ฑ„ํƒํ–ˆ๋‹ค!

let nm = readLine()!.split(separator: " ").map { Int(String($0))! }
let nums = readLine()!.split(separator: " ").map { Int(String($0))! }.sorted(by: <)
let N = nm[0]
let M = nm[1]


var result: [Int] = []
var visited = Array(repeating: false, count: N)

func dfs(num: Int) {
    
    if num == M {
        print(result.map({String($0)}).joined(separator: " "))
        return
    }
    
    for i in 0..<N {
        if visited[i] == false {
            visited[i] = true
            result.append(nums[i])
            dfs(num: num+1)
            visited[i] = false
            result.removeLast()
        }
    }
}

dfs(num: 0)
๋ฐ˜์‘ํ˜•