当前位置:网站首页>LeetCode-54

LeetCode-54

2022-07-05 06:17:00 GreedySnaker

To give you one m That's ok n Columns of the matrix matrix , Please follow Clockwise spiral sequence , Returns all elements in the matrix .

 Insert picture description here

class Solution {
    
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) 
    {
    
        vector <int> ans;
        if (matrix.empty())
        {
    
            return ans; // If it is empty , Go straight back to 
        }

        int up = 0; // Upper, lower, left and right boundaries 
        int down = matrix.size() - 1;
        int left = 0;
        int right = matrix[0].size() - 1;

        while (true)
        {
    
            for (int i = left; i <= right; ++i) 
            {
    
                // towards the right 
                ans.push_back(matrix[up][i]);
            }
            if (++up > down)/// Reset the upper boundary , If the upper boundary is greater than the lower boundary , Then the traversal is completed , The same below 
            {
    
                break; 
            }
            for (int i = up; i <= down; ++i)
            {
    
                // Down 
                ans.push_back(matrix[i][right]); 
            }
            if (--right < left) // Reset the boundary 
            {
    
                break;
            }
            for (int i = right; i >= left; --i)
            {
    
                // towards the left 
                ans.push_back(matrix[down][i]); 
            }
            if (--down < up)// Reset the lower boundary 
            {
    
                break;              
            }
            for (int i = down; i >= up; --i)
            {
    
                // Up 
                ans.push_back(matrix[i][left]); 
            }
            if (++left > right)// Reset the left boundary 
            {
    
                break; 
            }
        }
        return ans;
    }
};

Direct loop add array , At present, we can consider whether to add row arrays directly , Don't cycle

原网站

版权声明
本文为[GreedySnaker]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140618227053.html