import java.util.* fun main(args:Array) { val (w,h) = readLine()!!.split(" ").map { it.toInt() } Proc(w, h).getAns() } class Proc(val w:Int, val h:Int) { val map = (0 until h).map { a-> readLine()!!.split(" ").withIndex().map { b-> Pos(b.index, a, b.value.toInt(), w) } } val dic = (0 until h).map { (0 until w).map { mutableMapOf() } } public fun getAns() { val queue = LinkedList() queue.push(Task(map[0][0], null, 0)) while (queue.isNotEmpty()) { val t = queue.pop() val prevKey = t.prev?.let { it.index }?:-1 if(dic[t.current.y][t.current.x].containsKey(prevKey) && dic[t.current.y][t.current.x][prevKey]!! <= t.step) { continue } dic[t.current.y][t.current.x][prevKey] = t.step for(i in (t.current.y - 1..t.current.y + 1)) { if(i < 0 || i > map.lastIndex) { continue } for(j in (t.current.x - 1.. t.current.x + 1)) { if(j < 0 || j > map[i].lastIndex) { continue } if(i == t.current.y && j == t.current.x) { continue } if(i != t.current.y && j != t.current.x) { continue } if(t.prev != null) { if(i == t.prev.y && j == t.prev.x) { continue } val tmp = listOf(t.prev.z, t.current.z, map[i][j].z) if(tmp.distinct().size != 3) { continue } if(tmp.max() != tmp[1] && tmp.min() != tmp[1]) { continue } } queue.push(Task(map[i][j], t.current, t.step + 1)) } } } var ans = dic[dic.lastIndex].let { it[it.lastIndex] }.let { if(it.isEmpty()) -1 else it.minBy { it.value }!!.value } if(ans <= 0) { ans = -1 } println(ans) } class Pos(val x:Int, val y:Int, val z:Int, val w:Int) { val index = y * w + x } class Task(val current:Pos, val prev:Pos?, val step:Int) }