剑指offer--代码题目3--顺时针打印矩阵

剑指offer--代码题目3--顺时针打印矩阵


         我在牛客网刷题,用的都是C++语言,解题思路都一样。这个题如果理清打印顺序,其实不难。

         解题思路:顺时针打印就是按圈数循环打印,所以先算圈数,一圈包含两行或者两列,比较行和列哪个小,小的就是圈数。在打印的时候会出现某一圈中只包含一行。用左上和右下的坐标定位出一次要旋转打印的数据,一次旋转打印结束后,往对角分别前进和后退一个单位。提交代码时,主要的问题出在没有控制好后两个for循环,需要加入条件判断,防止出现单行或者单列的情况。

       图解如下:

代码如下:

注意代码中防止越界的两个判断,if (top != bottom),if (left != right)

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        int row = matrix.size();   //行
        int col = matrix[0].size(); //列
        vector<int> res;
         
        // 输入的二维数组非法,返回空的数组
        if (row == 0 || col == 0)  return res;
         
        // 定义四个关键变量,表示左上和右下的打印范围
        int left = 0, top = 0, right = col - 1, bottom = row - 1;
        while (left <= right && top <= bottom)
        {
            // 1.left to right
            for (int i = left; i <= right; ++i)  res.push_back(matrix[top][i]);
            // 2.top to bottom
            for (int i = top + 1; i <= bottom; ++i)  res.push_back(matrix[i][right]);
            // 3.right to left
            if (top != bottom)
            for (int i = right - 1; i >= left; --i)  res.push_back(matrix[bottom][i]);
            // 4.bottom to top
            if (left != right)
            for (int i = bottom - 1; i > top; --i)  res.push_back(matrix[i][left]);
            left++,top++,right--,bottom--;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41103495/article/details/108602165