SW Test/Programmers

[Programmers] Lv2. N-Queen(kotlin)

An effort will never betray 😎 2022. 7. 26. 19:08
λ°˜μ‘ν˜•

문제

https://school.programmers.co.kr/learn/courses/30/lessons/12952?language=kotlin

 

 

μ˜ˆμ‹œ

https://school.programmers.co.kr/learn/courses/30/lessons/12952?language=kotlin

 

 

풀이

  • N-Queen은 λ°±νŠΈλž˜ν‚Ήμ˜ λŒ€ν‘œμ μΈ 문제둜 y좕을 ν•˜λ‚˜μ”© λ‚΄λ €κ°€λ©΄μ„œ x좕을 ν•œλ²ˆ μˆœνšŒν•˜μ—¬ Queen이 λ†“μ•„μ§ˆ 수 μžˆλŠ” 곳을 μ°ΎλŠ” λ¬Έμ œμž…λ‹ˆλ‹€.
  • ν•˜λ‚˜μ”© νƒμƒ‰ν•˜λ©΄μ„œ 찾아도 λ˜μ§€λ§Œ μˆ˜ν•™μ μœΌλ‘œ μ’Œν‘œλ₯Ό ν™œμš©ν•˜μ—¬ 문제λ₯Ό ν’€λ©΄ λΉ λ₯΄κ²Œ ν’€ 수 μžˆμŠ΅λ‹ˆλ‹€.
  • λŒ€κ°μ„ λΌλ¦¬λ„ 같은 라인에 Queen이 있으면 μ•ˆλ˜λŠ”λ° μ’Œν‘œμ˜ κΈ°μšΈκΈ°λ‚˜ κ·œμΉ™μ„ ν†΅ν•΄μ„œ 같은 λŒ€κ°μ„ μΈμ§€ μ•„λ‹Œμ§€ μ•Œ 수 μžˆμŠ΅λ‹ˆλ‹€.
  • 였λ₯Έμͺ½ μ•„λž˜λ‘œ ν–₯ν•˜λŠ” λŒ€κ°μ„ μ—μ„œ y-x 값이 λ™μΌν•œ μ’Œν‘œλŠ” 같은 λŒ€κ°μ„  상에 μ‘΄μž¬ν•©λ‹ˆλ‹€.
  • λ§ˆμ°¬κ°€μ§€λ‘œ μ™Όμͺ½ μ•„λž˜λ‘œ ν–₯ν•˜λŠ” λŒ€κ°μ„ λΌλ¦¬λŠ” y+x 값이 λ™μΌν•©λ‹ˆλ‹€.
  • λ”°λΌμ„œ yμ’Œν‘œλŠ” ν•˜λ‚˜μ”© λ‚΄λ €κ°€λ©΄μ„œ xμ’Œν‘œλ§Œ 0λΆ€ν„° n-1κΉŒμ§€ μˆœνšŒν•˜μ—¬ dlist (down list), rdlist(right down list) , ldlist(left down list) 에 μΆ”κ°€ν•˜κ³  이미 μ’Œν‘œκ°’μ΄ ν¬ν•¨λ˜μ–΄ 있으면 κ±΄λ„ˆλ›°λ©΄ λ©λ‹ˆλ‹€.
class Solution {
    var answer = 0
    
    fun backtraking(n: Int, y: Int, dlist: List<Int>, rdlist: List<Int>, ldlist: List<Int>){
        if(n == y){
            answer++
            return
        }
        
        (0 until n).forEach{ i ->
            if(dlist.contains(i).not() && rdlist.contains(y-i).not() && ldlist.contains(y+i).not()){
                backtraking(n, y+1, dlist + listOf(i), rdlist + listOf(y -i), ldlist + listOf(y + i))
            }
        }
    }
    
    fun solution(n: Int): Int {
        backtraking(n,0,listOf<Int>(), listOf<Int>(), listOf<Int>())
        return answer
    }
}

 

 

 

μ°Έκ³ 

 

contains - Kotlin Programming Language

 

kotlinlang.org

 

λ°˜μ‘ν˜•