顺时针打印数组

本文介绍了如何实现顺时针打印二维数组的方法,包括从外到内遍历和使用四个指针进行迭代的策略,适用于面试中的算法问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

/*
    思想,用左上和右下的坐标定位出一次要旋转打印的数据,一次旋转打印结束后,往对角分别前进和后退一个单位。
    提交代码时,主要的问题出在没有控制好后两个for循环,需要加入条件判断,防止出现单行或者单列的情况。
 */
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)
    
     for (int i = left; i <= right; ++i)  res.push_back(matrix[top][i]);   // left to right 
     for (int i = top + 1; i <= bottom; ++i)  res.push_back(matrix[i][right]);  // top to bottom
            
     if (top != bottom)                                          // right to left
      for (int i = right - 1; i >= left; --i)  res.push_back(matrix[bottom][i]);
           
     if (left != right)                                         // bottom to top
      for (int i = bottom - 1; i > top; --i)  res.push_back(matrix[i][left]);

      left++,top++,right--,bottom--;
    }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

屠变恶龙之人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值