C++ | Efficient Spiral Matrix III | 0ms Beats [100.00%]
Intuition\nNavigating a grid in a spiral pattern starting from a given point involves moving in specific directions while increasing the steps after every two t
# Intuition\nNavigating a grid in a spiral pattern starting from a given point involves moving in specific directions while increasing the steps after every two turns (right, down, left, up). We can simulate this by using direction vectors and dynamically adjusting the movement steps to ensure we cover all cells within the grid\'s boundaries.\n\n# Approach\nTo generate the spiral order of coordinates from a starting position **(rStart, cStart)**, we use an array to store the directions for right, down, left, and up movements. Starting with a step count of 1 and an initial direction (right), we move in the current direction for the given step count, adding valid grid positions to the result. After two turns, we increase the step count and change direction. This process continues until we visit all cells in the grid, ensuring the result list is filled in the correct spiral order.\n\n# Complexity\n- **Time complexity** $$O(\\text{rows} \\times \\text{cols})$$, as we visit each cell once.\n- **Space complexity** $$O(\\text{rows} \\times \\text{cols})$$, for storing the result.\n\n# Code\n```\nclass Solution {\npublic:\n    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        vector<vector<int>> result;\n        result.reserve(rows * cols); \n        vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; \n        int steps{1}, dirIndex{0}, totalCells = rows * cols;\n        result.push_back({rStart, cStart});\n        while (result.size() < totalCells) {\n            for (int j{0}; j < 2; ++j) { \n                for (int i{0}; i < steps; ++i) {\n                    rStart += directions[dirIndex][0];\n                    cStart += directions[dirIndex][1];\n                    if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {\n                        result.push_back({rStart, cStart});\n                    }\n                }\n                dirIndex = (dirIndex + 1) % 4;\n            }\n            steps++;\n        }        \n        return result;\n    }\n};\n\n```\n## **If you found this solution helpful, please upvote! \uD83D\uDE0A**\n
['C++']