Kotlin | BFS | O(n*m)
Code\n\nclass Solution {\n    fun minimumMoves(grid: Array<IntArray>): Int {\n        val visited = HashSet<Triple<Int, Int, Boolean>>()\n        val queue = Li
# Code\n```\nclass Solution {\n    fun minimumMoves(grid: Array<IntArray>): Int {\n        val visited = HashSet<Triple<Int, Int, Boolean>>()\n        val queue = LinkedList<Triple<Int, Int, Boolean>>() // i, j, isHorizontal\n        queue.add(Triple(0, 0, true))\n\n        var stepsCount = 0\n\n        while (queue.isNotEmpty()) {\n            for(k in 0 until queue.size) {\n                val position = queue.poll()\n                val (i, j, isHorizontal) = position\n\n                if (visited.contains(position)) continue\n                visited.add(position)\n\n                if (i == grid.lastIndex && j == grid[0].lastIndex - 1 && isHorizontal) {\n                    return stepsCount\n                }\n\n                if (isHorizontal) {\n                    if (i < grid.lastIndex && grid[i + 1][j] == 0 && grid[i + 1][j + 1] == 0) { // down\n                        queue.add(Triple(i + 1, j, true))\n                        queue.add(Triple(i, j, false))\n                    }\n                    if (j < grid[0].lastIndex - 1 && grid[i][j + 2] == 0) { // right\n                        queue.add(Triple(i, j + 1, true))\n                    }\n                } else {\n                    if (j < grid[0].lastIndex && grid[i][j + 1] == 0 && grid[i + 1][j + 1] == 0) { // right\n                        queue.add(Triple(i, j + 1, false))\n                        queue.add(Triple(i, j, true))\n                    }\n                    if (i < grid.lastIndex - 1 && grid[i + 2][j] == 0) { // down\n                        queue.add(Triple(i + 1, j, false))\n                    }\n                }\n            }\n\n            stepsCount++\n        }\n\n        return -1\n    }\n}\n```
['Kotlin']