Simple Easy to Understand Java solution
The idea here is that once we start at (r=r0, c=c0), we walk along the east, then south, then west, and then north. \n\nWhen we go east, we do c++ (column incre
The idea here is that once we start at (r=r0, c=c0), we walk along the east, then south, then west, and then north. \n\nWhen we go east, we do c++ (column increases), when we go west, we do c--, when we go south, we do r++ (row increases), and when we go north, we do r--.\n\nAfter starting at (r0,c0), we need to walk in spirals, where the length of the spiral increases after every two directions. For example 2, we start at (r0=1, c0=4), then we go east by one length, we go south by one length. Following that, we go west by 2 length and then, go north by 2 length. After that, we go in next directions by 3 lengths, and so on.\n\nThe trick here is that we continue to walk in spiral, whether the current (r,c) is valid or not. However, we add (r,c) to the result only if it is valid.\n\n```\nclass Solution {\n    int idx;\n    int[][] ret;\n    \n    private void add (int r, int c, int R, int C) {\n        if (r >= R || r < 0 || c >= C || c < 0) return;\n        ret[idx][0] = r;\n        ret[idx++][1] = c;\n    }\n    \n    public int[][] spiralMatrixIII(int R, int C, int r0, int c0) {\n        int r = r0, c = c0, len = 1;\n        ret = new int[R * C][2];\n        while (idx < (R * C )) {         \n            for (int k = 0; k < len; k++) add(r, c++, R, C);          \n            for (int k = 0; k < len; k++) add(r++, c, R, C);\n            len++;\n            for (int k = 0; k < len; k++) add(r, c--, R, C);\n            for (int k = 0; k < len; k++) add(r--, c, R, C);\n            len++;   \n        }\n        return ret;\n    }\n}\n```
[]