C++ clean code beat 96% with explanation
take a pen and paper, try to draw the path once by yourself, you will notice that\n\n\t\t\t       i    wanted steps\ngo right  by 1     0        1 = i/2+1\ngo d
**take a pen and paper, try to draw the path once by yourself, you will notice that**\n```\n\t\t\t       i    wanted steps\ngo right  by 1     0        1 = i/2+1\ngo down   by 1     1        1 = i/2+1\ngo left   by 2     2        2 = i/2+1\ngo up     by 2     3        2 = i/2+1\ngo right  by 3     4        3 = i/2+1\ngo down   by 3     5        3 = i/2+1\ngo left   by 4     6        4 = i/2+1\ngo up     by 4     7        4 = i/2+1\n...etc\n```\n**once we meet out of bound, don\'t add it to the answer and just going forward.**\n\n```\nclass Solution {\npublic:\n    int way[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};\n    vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {\n        vector<vector<int>> res;\n        res.push_back({r0,c0}); //put the source first\n        int direction = 0, end_cnt = 1;\n        for(int i = 0 ; end_cnt < R*C ; i++){\n            int cnt = i/2+1;\n            while(cnt--){\n                r0 += way[direction][0];\n                c0 += way[direction][1];\n                if(r0 >= 0 && r0 < R && c0 < C && c0 >= 0) // only when current node is a valid position, add vector to the answer. There is no duplicate node, don\'t worry.\n                    res.push_back({r0,c0}),end_cnt++;\n            }\n            direction = (direction+1)%4; //each i loop, change direction\n        }\n        return res;\n    }\n};\n```
[]