Best & simplest approach with comments | Simulation | O(rows * cols) | C++
Intuition & Approach\n Describe your first thoughts on how to solve this problem. \nJust simulate and keep steps we need to iterate for each row & column, along
# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust simulate and keep steps we need to iterate for each row & column, along with a direction bool (fwd) which decides if we are going forward or backward in a row or column\nalso ignore the out of bounds values to get the final matrix \n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(rows * cols)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(rows * cols)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart,\n                                        int cStart) {\n        int steps =\n            1; // steps for each rows & cols iteration to create a spiral\n        bool fwd = true; // forward direction\n        res.push_back({rStart, cStart});\n\n        while (res.size() < rows * cols) {\n            // traverse in row\n            for (int i = 0; i < steps; ++i) {\n                cStart = fwd ? ++cStart : --cStart;\n                checkAndPush(rStart, cStart, rows, cols);\n            }\n\n            // traverse in column\n            for (int i = 0; i < steps; ++i) {\n                rStart = fwd ? ++rStart : --rStart;\n                checkAndPush(rStart, cStart, rows, cols);\n            }\n\n            steps++;\n            fwd = !fwd;\n        }\n        return res;\n    }\n\nprivate:\n    vector<vector<int>> res;\n\n    // check if the indexes are lying inside the matrix\n    void checkAndPush(int rowIdx, int colIdx, int rows, int cols) {\n        if (rowIdx < rows && rowIdx >= 0 && colIdx < cols && colIdx >= 0)\n            res.push_back({rowIdx, colIdx});\n    }\n};\n\n```
['Matrix', 'Simulation', 'C++']