원본 문제 : 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
}
}
'코딩연습' 카테고리의 다른 글
[백준] ATM (11399)(Kotlin) (0) | 2020.02.20 |
---|---|
[백준] 상범 빌딩 (6593)(Kotlin) (0) | 2020.02.20 |
[백준] 특정한 최단 경로 (1504)(Kotlin) (0) | 2020.02.17 |
[백준] 알고스팟 (1261)(Kotlin) (0) | 2020.02.17 |
[백준] 파티 (1238)(Kotlin) (0) | 2020.02.17 |
댓글