Spiral Matrix III: Adapted DFS solution
Approach\nWe keep track of 5 main variables:\n1. x: colum number\n2. y: row number\n3. d: current direction\n3. visited: Set of Pairs of visited col & row\n4. r
# Approach\nWe keep track of 5 main variables:\n1. x: colum number\n2. y: row number\n3. d: current direction\n3. visited: Set of Pairs of visited col & row\n4. result: List of ordered visited pairs\n\nEach time we check the direction and possible x & y values :\n- if next position already visited: keep moving in the same current position.\n- if next position is not visited: update x & y\n\n**Grid\'s boundary**:\nMoving outside of the grid\'s boundary will not cause a problem if we ignore the positions in the final result. It is not needed to include the outer positions in the visited set. \n\n# Complexity\n- Time complexity: **O(n*m)**\n\n- Space complexity: **O(n*m)**\n\nNote: *n=rows, m=columns*\n\n# Code\n```\nenum class Direction {\n    RIGHT, DOWN, LEFT, UP\n}\n\nclass Solution {\n\n    fun spiralMatrixIII(rows: Int, cols: Int, rStart: Int, cStart: Int): Array<IntArray> {\n        val visited: MutableSet<Pair<Int, Int>> = mutableSetOf()\n        val result: MutableList<IntArray> = mutableListOf()\n        var y = rStart\n        var x = cStart\n        var d: Direction = Direction.UP\n        fun dfs() {\n            if (x in 0 until cols && y in 0 until rows) {\n                visited.add(Pair(y, x))\n                result.add(intArrayOf(y, x))\n            }\n            when (d) {\n                Direction.RIGHT -> {\n                    if (!visited.contains(Pair(y+1, x))) {y+=1; d=Direction.DOWN}\n                    else {x+=1; d=Direction.RIGHT}\n                }\n                Direction.DOWN -> {\n                    if (!visited.contains(Pair(y, x-1))) {x-=1; d=Direction.LEFT}\n                    else {y+=1; d=Direction.DOWN}\n                }\n                Direction.LEFT -> {\n                    if (!visited.contains(Pair(y-1, x))) {y-=1; d=Direction.UP}\n                    else {x-=1; d=Direction.LEFT}\n                }\n                Direction.UP -> {\n                    if (!visited.contains(Pair(y, x+1))) {x+=1; d=Direction.RIGHT}\n                    else {y-=1; d=Direction.UP}\n                }\n            }\n            if (visited.size == rows * cols){\n                return\n            } else { dfs() }\n        }\n        dfs()\n        return result.toTypedArray()\n    }\n}\n\n```
['Depth-First Search', 'Graph', 'Matrix', 'Kotlin']