题解 | #顺时针打印矩阵#

顺时针打印矩阵

https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

class Solution {
 public:
  vector<int> printMatrix(vector<vector<int> > matrix) {
    vector<int> res;
    int n = matrix.size();
    if( n == 0){
      return res;
    }
    int left = 0;
    int right = matrix[0].size()-1; //这里需要注意的是矩阵不一定是方阵,很容易想当然地认为是n-1;
    int top = 0;
    int bottom = n-1;
    while(left<=right && top <= bottom){
      //最上面一行从左往右
      for(int i = left;i<=right;i++)
      {
        res.push_back(matrix[top][i]);
      }
      //最上面一行扫描完毕
      top++;
      if(top > bottom){
        break;
      }
      //最右面一列从上往下
      for(int i = top; i<= bottom;i++)
      {
        res.push_back(matrix[i][right]);
      }
      //最右边一列扫描完毕
      right--;
      if(left > right){
        break;
      }
      //最下面一行从右往左
      for(int i = right;i>=left;i--)
      {
        res.push_back(matrix[bottom][i]);
      }
      bottom--;
      if(top > bottom)
      {
        break;
      }
      //最左边一列从下往上
      for(int i = bottom;i>=top;i--)
      {
        res.push_back(matrix[i][left]);
      }
      left++;
      if(left > right){
        break;
      }
    }
    return res;
  }


};

模拟法,I got it!

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务