Better solution for easy understanding
\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 
\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[][] mat = new int[rows*cols][2];\n        int i = 0;\n        mat[i++] = new int[]{rStart,cStart};\n        int d = 0;\n        int len = 0;\n        int[] directions = {0,1,0,-1,0};\n\n        while(i < rows*cols){\n            if(d==0 || d==2) len++;\n\n            for (int j = 0; j < len; j++) {\n                rStart += directions[d];\n                cStart += directions[d+1];\n                if(rStart < rows && rStart >= 0 && cStart < cols && cStart >= 0) mat[i++] = new int[]{rStart, cStart};\n            }\n            d = ++d%4;\n        }\n        return mat;\n        \n    }\n}\n```
['Java']