1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import java.util.*
var n = 0 var m = 0 var dx = intArrayOf(1, 0, -1, 0) var dy = intArrayOf(0, 1, 0, -1) lateinit var maze: Array<IntArray> lateinit var visit: Array<BooleanArray>
fun main() { init() println(bfs()) }
fun bfs() : Int { val queue: Queue<Triple<Int, Int, Int>> = LinkedList() queue.offer(Triple(0, 0, 1)) visit[0][0] = true
while (queue.isNotEmpty()) { val (curX, curY, count) = queue.poll() for (dir in 0 until 4) { val (nx, ny) = curX + dx[dir] to curY + dy[dir]
if (nx == n - 1 && ny == m - 1) { return count + 1 }
if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue if (visit[nx][ny] || maze[nx][ny] == 0) continue
visit[nx][ny] = true queue.add(Triple(nx, ny, count + 1)) } } return 0 }
fun init() = with(Scanner(System.`in`)) { n = nextInt() m = nextInt() maze = Array(n) { IntArray(m) } visit = Array(n) { BooleanArray(m) }
for (i in 0 until n) { val line = next() for (j in 0 until m) { maze[i][j] = Character.getNumericValue(line[j]) } } }
|