Kotlin. Beats 100% (240 ms). OOP approach.
\n\n# Code\n\nclass Solution {\n    fun spiralMatrixIII(rows: Int, cols: Int, rStart: Int, cStart: Int): Array<IntArray> {\n        reset()\n\n        val pathR
![image.png](https://assets.leetcode.com/users/images/6b30340b-fb0e-424b-8204-6b55a9dbd4b2_1723143380.2573102.png)\n\n# Code\n```\nclass Solution {\n    fun spiralMatrixIII(rows: Int, cols: Int, rStart: Int, cStart: Int): Array<IntArray> {\n        reset()\n\n        val pathRecorder = PathRecorder(rows, cols)\n        var direction = directions[0]\n        var vy = rStart\n        var vx = cStart\n        while (pathRecorder.isIncomplete()) {\n            for (c in 0 until direction.maxSteps) {\n                if (vy >= 0 && vy < rows && vx >= 0 && vx < cols) {\n                    pathRecorder.addCell(vy, vx)\n                }\n                vx += direction.dx\n                vy += direction.dy\n            }\n            direction.maxSteps += 2\n            direction = direction.next!!\n        }\n        return pathRecorder.path()\n    }\n\n    class Direction(val dx: Int, val dy: Int, var maxSteps: Int) {\n        var next: Direction? = null\n    }\n\n    class PathRecorder(rows: Int, cols: Int) {\n        val result = Array<IntArray?>(rows * cols) { null }\n        var i = 0\n\n        inline fun isIncomplete(): Boolean {\n            return i < result.size\n        }\n\n        inline fun addCell(row: Int, col: Int) {\n            result[i++] = intArrayOf(row, col)\n        }\n\n        fun path(): Array<IntArray> {\n            return result as Array<IntArray>\n        }\n    }\n\n    companion object {\n        val directions = arrayOf(\n            Direction(1, 0, 1),\n            Direction(0, 1, 1),\n            Direction(-1, 0, 1),\n            Direction(0, -1, 1)\n        )\n        init {\n            directions[0].next = directions[1]\n            directions[1].next = directions[2]\n            directions[2].next = directions[3]\n            directions[3].next = directions[0]\n        }\n        fun reset() {\n            directions[0].maxSteps = 1\n            directions[1].maxSteps = 1\n            directions[2].maxSteps = 2\n            directions[3].maxSteps = 2\n        }\n    }\n}\n```
['Kotlin']