💡Swift - Optimal Solution - Breadth-First Search
Solution\n\nclass Solution {\n    struct Index: Hashable {\n        let x, y: Int\n    }\n    func nearestExit(_ maze: [[Character]], _ entrance: [Int]) -> Int 
# Solution\n```\nclass Solution {\n    struct Index: Hashable {\n        let x, y: Int\n    }\n    func nearestExit(_ maze: [[Character]], _ entrance: [Int]) -> Int {\n        let n = maze.count\n        let m = maze[0].count\n\n        let startIndex = Index(x: entrance[1], y: entrance[0])\n\n        var visited: Set<Index> = [startIndex]\n        var queue: Set<Index> = [startIndex]\n\n        var steps = 0\n        while !queue.isEmpty {\n            steps += 1\n    \n            var nextQueue: Set<Index> = []\n            for index in queue {\n                for (dX, dY) in [(-1, 0), (0, -1), (1, 0), (0, 1)] {\n                    let next = Index(x: index.x + dX, y: index.y + dY)\n\n                    // Validate the index is inside the bounds.\n                    guard 0..<m ~= next.x && 0..<n ~= next.y else { continue }\n\n                    // Validate it\'s not a wall. \n                    guard maze[next.y][next.x] == "." else { continue }\n\n                    guard visited.insert(next).inserted else { continue }\n                    nextQueue.insert(next)\n\n                    // Check if it\'s an exit.\n                    if (next.x == 0 || next.x == m - 1 || next.y == 0 || next.y == n - 1) {\n                        return steps\n                    }\n                }\n            }\n            queue = nextQueue\n        }\n\n        return -1\n    }\n}\n```\n# Complexity\n- Time: $$O(n \\cdot m)$$\n- Space: $$O(max(n, m))$$
['Breadth-First Search', 'Swift']