🔥Java beats 100%, 0ms runtime || Easy to Understand
Complexity\n- Time complexity: O(rows * cols)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(N)\n Add your space complexity here, e.g. O(n
# Complexity\n- Time complexity: O(rows * cols)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        int[][] matrix = new int[rows*cols][2];\n        int k = 0;\n        \n        int rEnd = rStart + 1;\n        int cEnd = cStart + 1;\n\n        while(true) {\n            // right \n            for(int i = cStart; i <= cEnd; i++) {\n                if(i < cols && i >= 0 && rStart >= 0) {\n                    matrix[k][0] = rStart;\n                    matrix[k][1] = i;\n                    k++;\n                }\n            }\n            cStart--;\n            cEnd++;\n\n            if(k == matrix.length) {\n                break;\n            }\n\n            // down \n            for(int i = rStart + 1; i <= rEnd; i++) {\n                if(i < rows && i >= 0 && cEnd - 1 < cols) {\n                    matrix[k][0] = i;\n                    matrix[k][1] = cEnd - 1;\n                    k++;\n                }\n            }\n            rStart--;\n            rEnd++;\n\n            if(k == matrix.length) {\n                break;\n            }\n\n            // left\n            for(int i = cEnd - 2; i >= cStart; i--) {\n                if(i >= 0 && i < cols && rEnd - 1 < rows) {\n                    matrix[k][0] = rEnd - 1;\n                    matrix[k][1] = i;\n                    k++;\n                }\n            }\n        \n            if(k == matrix.length) {\n                break;\n            }\n\n            // up\n            for(int i = rEnd - 2; i > rStart; i--) {\n                if(i >= 0 && i < rows && cStart >= 0) {\n                    matrix[k][0] = i;\n                    matrix[k][1] = cStart;\n                    k++;\n                }\n            }\n        \n            if(k == matrix.length) {\n                break;\n            }\n        }\n        return matrix;\n    }\n}\n```
['Matrix', 'Java']