Leetcode 54. Spiral Matrix

Given a matrix containing m x n elements (m rows, n columns), return all elements in the matrix in a clockwise spiral order.

Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]

Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

Train of thought: Traverse layer by layer. Note that the layer here refers to every circle of a two-dimensional array from outside to inside. The number of layers is row/2 (half of the number of rows in the array). Then go clockwise through the layer from the upper left corner (traversing four edges). Note the index value of each element here. Then, in order to prevent this two-dimensional array from having only one row, you need to press into each of the layers. After the bar edge, it is necessary to determine whether to traverse the entire two-dimensional array. If the traversal is completed, it will exit directly, and the target vector has got all the values.

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> vecRes;
        if(matrix.empty())
            return vecRes;
        int row = matrix.size();
        int col = matrix[0].size();
        int i=0,total = row*col;
        while(i<=row/2)
        {
            int m=i;
            int n=i;
            int temp=i;
            while(n<=col-temp-1)
            {
                vecRes.push_back(matrix[m][n]);
                n++;
            }
            if(vecRes.size() == total)
                    break;
            n--;
            m++;
            while(m<=row-temp-1)
            {
                vecRes.push_back(matrix[m][n]);
                m++;
            }
            if(vecRes.size() == total)
                    break;
            m--;
            n--;
            while(n>=temp)
            {
                vecRes.push_back(matrix[m][n]);
                n--;
            }
            if(vecRes.size() == total)
                    break;
            n++;
            m--;
            while(m>temp)
            {
                vecRes.push_back(matrix[m][n]);
                m--;
            }
            i++;
        }
        return vecRes;
    }
};

Posted by giannitom on Tue, 02 Apr 2019 15:24:28 -0700