An Accept 0ms C++ solution, I think it is easy to understand


  • 0
    Y
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> result;
    	    if (matrix.size() == 0)return result;
    	    int rows = matrix.size();
    	    int cols = matrix.at(0).size();
    	    printTurn(matrix, result, 0, rows, 0, cols);
    	    return result;
        }
    private:
        void printTurn(vector<vector<int>>& matrix, vector<int>& result, int r_s, int r_e, int c_s, int c_e)
    {
    	if (r_s >= r_e || c_s >= c_e)return;
    	if (r_e == r_s + 1)
    	{
    		for (int j = c_s; j < c_e; ++j)
    			result.push_back(matrix.at(r_s).at(j));
    		return;
    	}
    	if (c_e == c_s + 1)
    	{
    		for (int i = r_s; i < r_e; ++i)
    			result.push_back(matrix.at(i).at(c_s));
    		return;
    	}
    	for (int j = c_s; j < c_e - 1; ++j)
    		result.push_back(matrix.at(r_s).at(j));
    	for (int i = r_s; i < r_e - 1; ++i)
    		result.push_back(matrix.at(i).at(c_e - 1));
    	for (int j = c_e - 1; j > c_s; --j)
    		result.push_back(matrix.at(r_e - 1).at(j));
    	for (int i = r_e - 1; i > r_s; --i)
    		result.push_back(matrix.at(i).at(c_s));
    	printTurn(matrix, result, r_s + 1, r_e - 1, c_s + 1, c_e - 1);
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.