C++ from approach to implementation explained
Observation 1- How to traverse\nIn this approach I have traversed the path of the spiral after making a few observations. If you refer \nExample 2, R = 5, C = 6
# Observation 1- How to traverse\nIn this approach I have traversed the path of the spiral after making a few observations. If you refer \nExample 2, R = 5, C = 6, r0 = 1, c0 = 4, you will notice the direction of the walk does not change\nfrom 1 to 2, \n2 to 3, \n3 to 5,\n5 to 7, ....\nHere  2-1 = 3-2\n5-3 = 7-5\n![image](https://assets.leetcode.com/users/debipur/image_1579243848.png)\nThis brings us to our first observation, the length of the line along which direction does not change\nremains equal after the odd number of changes and after even direction changes the length \nincreases by 1.\n# Approach\nSo, our approach here is we keep track of our current coordinates. Also have a array which stores the\nchange required to move right, down, left and up respectively :- {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}.\nAccording to the no. of steps taken, position in current line and no. of direction changes we make \nthe change to our current cordinate. At each coordinate we check whether it is a valid cell, if so we \npush it to answer.\n```\ninline bool isvalid(vector<int> &cur, int R, int C){\n\tif(cur[0] >= 0 && cur[1] >= 0 && cur[0] < R && cur[1] < C)\n\t\treturn true;\n\treturn false;\n}\n```\n# Observation 2- How long to traverse\nThe question is how long we need to move? If you draw(rather imagine) the spiral, for the following\nboundary case it answers our question, R = 100, C = 1, r0 = 0, c0 = 0. You will find (2*max(R, C))^2 is\nthe maximum number of steps you will need.\n```\nvector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {\n        vector<vector<int>> ans;\n        vector<int> cur = {r0, c0};\n        ans.push_back(cur);\n        vector<vector<int>> dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        int totsteps = 2*max(R, C); totsteps*=totsteps;\n\t\tint stepi = 0, d = 0;                    //tracks i th step and d th direction change\n        int linelen = 1;\n        while(stepi <= totsteps){\n            for(int a = 1; a <=2; ++a){          // looping twice for same length\n                int k = 1;                       //tracks steps taken in current line\n                while(k <= linelen){\n                    cur[0] += dir[d][0];\n                    cur[1] += dir[d][1];\n                    if(isvalid(cur, R, C)) ans.push_back(cur);\n                    k++; stepi++;\n                }\n                d = (d+1)%4;\n            }\n            linelen++;\n        }\n        return ans;\n    }\n```\nMy first post here in leetcode :)\nLet me know if this helped or did I leave out details.
['Math', 'C', 'C++']