Java | TC: O(max(R, C)^2) | SC: O(1) | Simulating a Spiral Walk
java\n/**\n * Distance covered in each direction follows 1, 1, 2, 2, 3, 3, 4, 4... pattern.\n *\n * Order of directions: Right, Down, Left, Up. Whenever the dir
```java\n/**\n * Distance covered in each direction follows 1, 1, 2, 2, 3, 3, 4, 4... pattern.\n *\n * Order of directions: Right, Down, Left, Up. Whenever the direction becomes\n * right or left, the distance travelled in that direction increases by 1.\n *\n * So the distance travelled is sum of 1, 1, 2, 2, ... 2*max(R,C), 2*max(R,C).\n *\n * Time Complexity: O(max(R, C)^2)\n *\n * Space Complexity: O(1) -> Excluding the result.\n *\n * R = Input number of rows. C = Input number of columns.\n */\nclass Solution {\n    public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        if (rows < 0 || cols < 0 || rStart < 0 || rStart >= rows || cStart < 0 || cStart >= cols) {\n            throw new IllegalArgumentException("Input is invalid");\n        }\n\n        int totalLen = rows * cols;\n        int[][] result = new int[totalLen][2];\n        result[0] = new int[] { rStart, cStart };\n        if (totalLen == 1) {\n            return result;\n        }\n\n        int dist = 0;\n        int row = rStart;\n        int col = cStart;\n        int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };\n        int dirIdx = 0;\n        int count = 1;\n\n        while (count < totalLen) {\n            if (dirIdx == 0 || dirIdx == 2) {\n                dist++;\n            }\n            for (int i = 1; i <= dist; i++) {\n                row += dirs[dirIdx][0];\n                col += dirs[dirIdx][1];\n                if (row >= 0 && row < rows && col >= 0 && col < cols) {\n                    result[count++] = new int[] { row, col };\n                    if (count == totalLen) {\n                        return result;\n                    }\n                }\n            }\n            dirIdx = (dirIdx + 1) % 4;\n        }\n\n        return result;\n    }\n}\n```\n\n---\n\nSolutions to other parts of Spiral Matrix question on LeetCode:\n- [54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/discuss/1511476/Java-or-TC:-O(M*N)-or-SC:-O(1)-or-Optimized-solution-using-Switch-Case)\n- [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/discuss/1511479/Java-or-TC:-O(N2)-or-SC:-O(1)-or-Multiple-optimized-ways-to-solve-this-question)
['Array', 'Matrix', 'Simulation', 'Java']