Efficient C++ Solution
class Solution {\npublic:\n    vector> spiralMatrixIII(int rows, int cols, int i, int j) {\n\t\n\t   // vector where we will store our elements indices { i , j 
class Solution {\npublic:\n    vector<vector<int>> spiralMatrixIII(int rows, int cols, int i, int j) {\n\t\n\t   // vector where we will store our elements indices { i , j }\n       vector<vector<int>> matrix(rows*cols,vector<int>(2)); \n\t\tint x=2;            // value to be used and incremented step by step\n        int k=rows*cols,n1=0;      // max value is rows*cols\n        int steps=1,t;      //  number of steps to go in any direction, we will increase this time to time\n        matrix[n1++]={i,j};       // initialized first indice\n        while(x<=k){\n            \n\t\t\t// now first we will traverse steps number of steps in right direction\n\t\t\t// at every step, we will check if its a valid matrix indice or not\n\t\t\tt=steps;\n            while(t--){\n                j++;\n                if( j<cols && i<rows && j>=0 && i>=0) {\n\t\t\t\t// for any valid indice, we will store that indice in matrix and increment x\n                    matrix[n1++]={ i , j };\n                    x++;\n                }\n            }\n\t\t\t\n\t\t\t// now we will traverse same number of steps vertically down \n            t=steps;\n            while(t--){\n                i++;\n                if( j<cols && i<rows && j>=0 && i>=0) {\n                    matrix[n1++]={ i , j };\n                    x++;\n                }\n            }\n\t\t\t// now we will traverse steps+1 number of steps in left direction\n            steps++;\n            t=steps;\n            while(t--){\n                j--;\n                if( j<cols && i<rows && j>=0 && i>=0) {\n                    matrix[n1++]={ i , j };\n                    x++;\n                }\n            }\n\t\t\t\n\t\t\t// now we will traverse same number of steps vertically upward \n            t=steps;\n            while(t--){\n                i--;\n                if( j<cols && i<rows && j>=0 && i>=0) {\n                    matrix[n1++]={ i , j };\n                    x++;\n                }\n            }\n\t\t\t// now we again increase steps by 1 to maintain clockwise motion\n            l++;\n        }\n        return matrix;  // our matrix is ready \n    }\n// NOTE:- To understand the code, have a look at the given sample examples and understand the motion.\n// If understood the concept then please press the up arrow on the left of this solution.\n};\n\n
[]