IT/알고리즘

[백준] 패턴

남갯 2024. 10. 30. 21:16
SMALL

 

https://www.acmicpc.net/status?from_problem=1&problem_id=17300

 

fun main() = with(Scanner(System.`in`)) {
    val count = nextInt()
    val pattern = Array<Int>(count) { 0 }
    for (i in 0 until count) {
        pattern[i] = nextInt()
    }

    val visited: Array<Array<Boolean>> = arrayOf(
        arrayOf(false, false, false),
        arrayOf(false, false, false),
        arrayOf(false, false, false)
    )
    println(if (find(0, pattern, visited)) "YES" else "NO")
}
// 0,0 0,1 0,2
// 1,0 1,1 1,2
// 2,0 2,1 2,2
// 1    2   3
// 4    5   6
//

fun find(index: Int, pattern: Array<Int>, visited: Array<Array<Boolean>>): Boolean {
    if (index == pattern.size - 1) {
        return true
    }
    val current = pattern[index]
    val next = pattern[index + 1]

    val x = (current - 1) / 3
    val y = (current - 1) % 3

    val targetX = (next - 1) / 3
    val targetY = (next - 1) % 3

    if (abs(targetX - x) <= 1 && abs(targetY - y) <= 1 || (abs(targetX - x) == 2 || abs(targetY - y) == 2)) {
        if (visited[targetX][targetY]) {
            return false
        } else {
            visited[targetX][targetY] = true
            if (abs(targetX - x) == 2 && abs(targetY - y) == 2 && !visited[1][1])
                return false
            else if (abs(targetX - x) == 2 && abs(targetY - y) == 0 && !visited[1][targetY]) {
                return false
            } else if (abs(targetY - y) == 2 && abs(targetX - x) == 0 && !visited[targetX][1]) {
                return false
            }
            return find(index + 1, pattern, visited)
        }
    }
    return false
}
LIST