본문 바로가기
코딩연습

[백준] 녹색 옷 입은 애가 젤다지? (4485)(Kotlin)

by 유줘니 2020. 2. 19.

원본 문제 : https://www.acmicpc.net/problem/4485

 

<첫번째>

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*

var n: Int = 0
var map: Array<IntArray> = arrayOf()
var distance: Array<IntArray> = arrayOf()
var cnt: Int = 1

val dRow: IntArray = intArrayOf(-1,1,0,0)
val dCol: IntArray = intArrayOf(0,0,-1,1)

fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {

    n = readLine().toInt()

    while ( n != 0 ) {

        map = Array( n + 1 ) { IntArray( n + 1 ) }
        distance = Array( n + 1 ) { IntArray( n + 1) }

        for ( i in 1 until n + 1 ) {
            val str = readLine().split(" " )
            for ( j in 1 until n + 1 ) {
                map[i][j] = str[j-1].toInt()
            }
        }

        for ( i in 1 until n + 1) {
            Arrays.fill(distance[i], 100000)
        }

        dijkstra()

        n = readLine().toInt()
    }
}

fun dijkstra() {
    val pq: PriorityQueue<Node> = PriorityQueue<Node>()

    distance[1][1] = map[1][1]
    pq.add( Node( 1, 1, 0 ) )

    while ( !pq.isEmpty() ) {
        val now = pq.poll()

        for ( i in 0 until 4 ) {
            val nextC = now.col + dCol[i]
            val nextR = now.row + dRow[i]

            if ( nextC <= 0 || nextR <= 0 || nextR > n || nextC > n ) continue

            if ( distance[nextC][nextR] > distance[now.col][now.row] + map[nextC][nextR] ) {
                distance[nextC][nextR] = distance[now.col][now.row] + map[nextC][nextR]
                pq.add( Node( nextC, nextR, distance[nextC][nextR] ) )
            }
        }
    }

    println("Problem ${cnt++}: ${distance[n][n]}")

}

class Node : Comparable<Node> {
    var col: Int = 0
    var row: Int = 0
    var cost: Int = 0

    constructor(col: Int, row: Int, cost: Int) {
        this.col = col
        this.row = row
        this.cost = cost
    }

    override fun compareTo(other: Node): Int {
        return this.cost - other.cost
    }
}

댓글