顺时针打印矩阵

in 知识共享 with 0 comment

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

 

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

本人提交代码

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        if ( matrix.empty() )
            return result;
        int rowNum = matrix.size();
        int colNum = matrix.front().size();

        int l = 0;
        int r = colNum - 1;
        int t = 0;
        int b = rowNum - 1;
        
        while ( true )
        {
            // top
            for ( int i = l; i <= r; i++ )
                result.push_back( matrix[t][i] );

            if ( ++t > b )
                break;

            // right
            for ( int i = t; i <= b; i++ )
                result.push_back( matrix[i][r] );

            if ( --r < l )
                break;

            // bottom
            for ( int i = r; i >= l; i-- )
                result.push_back( matrix[b][i] );

            if ( --b < t )
                break;

            // left
            for ( int i = b; i >= t; i-- )
                result.push_back( matrix[i][l] );
            
            if ( ++l > r )
                break;
        }
        

        return result;  
    }
};
Responses