Simplest Solution to Beat 99% - Clear and Easy to Understand! Right, Up, Down, Left Approach..
Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve the problem, we need to generate the coordinates of the cells in a spiral orde
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve the problem, we need to generate the coordinates of the cells in a spiral order starting from a given starting position. By expanding the movement in a spiral manner, we ensure that all cells in the matrix are covered.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Start at the initial position (rs, cs).\n2. Use four directions (right, down, left, up) to navigate the matrix.\n3. Expand the step size after completing two directions (right and down, left and up).\n4. Ensure that we only record coordinates within the bounds of the matrix.\n5. Repeat the process until all cells are visited.\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n    We visit each cell exactly once, where n is the total number of cells (rows * cols).\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n    We store all the coordinates of the cells in the result vector.\n\n# Code\n```\nclass Solution {\npublic:\n    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rs, int cs) {\n        int n = rows * cols;\n        int x = 1, y = 1;\n        vector<vector<int>> result;\n\n        while (result.size() < n) {\n            // right\n            for (int i = 0; i < x; i++) {\n                if (rs >= 0 && rs < rows && cs >= 0 && cs < cols) {\n                    result.push_back({rs, cs});\n                }\n                cs++;\n            }\n            x++;\n\n            // down\n            for (int i = 0; i < y; i++) {\n                if (rs >= 0 && rs < rows && cs >= 0 && cs < cols) {\n                    result.push_back({rs, cs});\n                }\n                rs++;\n            }\n            y++;\n\n            // left\n            for (int i = 0; i < x; i++) {\n                if (rs >= 0 && rs < rows && cs >= 0 && cs < cols) {\n                    result.push_back({rs, cs});\n                }\n                cs--;\n            }\n            x++;\n\n            // up\n            for (int i = 0; i < y; i++) {\n                if (rs >= 0 && rs < rows && cs >= 0 && cs < cols) {\n                    result.push_back({rs, cs});\n                }\n                rs--;\n            }\n            y++;\n        }\n\n        return result;\n    }\n};\n```\n\n# **Please upvote**\n![image.png](https://assets.leetcode.com/users/images/f65e2e94-d202-43a2-b72e-3be8f6775e8c_1723092142.6131754.png)\n
['Array', 'Matrix', 'Simulation', 'C++']