import java.util.* fun main(args: Array) { val (w, h) = readLine()!!.split(" ").map { it.toInt() } val map = (1..h).map { readLine()!!.split(" ").map { it.toInt() } } val step = Array(h){ Array(w) { mutableMapOf() } } val queue = LinkedList() queue.add(Pos(0,0)) step[0][0][null] = Step(0, null) while (queue.isNotEmpty()) { val cur = queue.pop() step[cur.r][cur.c].values.forEach { s -> val next = listOf(Pos(cur.r-1, cur.c), Pos(cur.r+1, cur.c), Pos(cur.r, cur.c-1), Pos(cur.r, cur.c+1)) for(n in next) { if(n.r !in map.indices) { continue } if(n.c !in map[n.r].indices) { continue } if(step[n.r][n.c][map[cur.r][cur.c]]?.step?:200 <= s.step + 1) { continue } if(s.prev == map[n.r][n.c]) { continue } if(map[cur.r][cur.c] == map[n.r][n.c]) { continue } var isValid = false s.prev?.let { prev -> val list = listOf(prev, map[cur.r][cur.c], map[n.r][n.c]).sorted() map[cur.r][cur.c].let { if(list[0] == it || list[2] == it) { isValid = true } } }?: run { isValid = true } if(isValid) { step[n.r][n.c][map[cur.r][cur.c]] = Step(s.step + 1, map[cur.r][cur.c]) queue.add(n) } } } } println(step.last().last().values.firstOrNull()?.step?:-1) } data class Step(val step:Int, val prev:Int?) data class Pos(val r:Int, val c:Int)