|
| 1 | +object Solution { |
| 2 | + import scala.collection.mutable |
| 3 | + |
| 4 | + private def isBorderCell(row: Int, col: Int, rows: Int, cols: Int): Boolean = { |
| 5 | + row == 0 || row == rows - 1 || col == 0 || col == cols - 1 |
| 6 | + } |
| 7 | + |
| 8 | + def nearestExit(maze: Array[Array[Char]], entrance: Array[Int]): Int = { |
| 9 | + val rows = maze.length |
| 10 | + val cols = maze(0).length |
| 11 | + val directions = Array((0, 1), (1, 0), (0, -1), (-1, 0)) |
| 12 | + val visited = mutable.Set.empty[(Int, Int)] |
| 13 | + val (entranceRow, entranceCol) = (entrance(0), entrance(1)) |
| 14 | + visited.addOne((entranceRow, entranceCol)) |
| 15 | + val queue = mutable.Queue.empty[(Int, Int, Int)] |
| 16 | + queue.enqueue((entranceRow, entranceCol, 0)) |
| 17 | + |
| 18 | + while (queue.nonEmpty) { |
| 19 | + val (row, col, steps) = queue.dequeue() |
| 20 | + if (isBorderCell(row, col, rows, cols) && (row, col) != (entranceRow, entranceCol)) { |
| 21 | + return steps |
| 22 | + } |
| 23 | + |
| 24 | + for ((dr, dc) <- directions) { |
| 25 | + val newRow = row + dr |
| 26 | + val newCol = col + dc |
| 27 | + if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) { |
| 28 | + if (maze(newRow)(newCol) == '.' && !visited.contains((newRow, newCol))) { |
| 29 | + queue.enqueue((newRow, newCol, steps + 1)) |
| 30 | + visited.addOne((newRow, newCol)) |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + -1 |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +Solution.nearestExit( |
| 40 | + Array( |
| 41 | + Array('+','+','.','+'), |
| 42 | + Array('+','+','.','+'), |
| 43 | + Array('+','+','.','+'), |
| 44 | + Array('+','.','.','+'), |
| 45 | + Array('+','+','+','+') |
| 46 | + ), |
| 47 | + Array(3, 1) |
| 48 | +) |
| 49 | + |
| 50 | +Solution.nearestExit( |
| 51 | + Array( |
| 52 | + Array('+','.','+','+','+','+','+'), |
| 53 | + Array('+','.','+','.','.','.','+'), |
| 54 | + Array('+','.','+','.','+','.','+'), |
| 55 | + Array('+','.','.','.','+','.','+'), |
| 56 | + Array('+','+','+','+','+','.','+') |
| 57 | + ), |
| 58 | + Array(0, 1) |
| 59 | +) |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
0 commit comments