剑指offer 66题 -- 顺时针打印矩阵

class Solution {
public:
  vector<int> printMatrix(vector<vector<int> > matrix) {
    //变量定义区
    int row = matrix.size();
    int col = matrix[0].size();
    vector<int> result;
    int start =0;

    //入参检查
    if(matrix.empty() || matrix[0].empty())
      return result;

    while(row > start*2 && col > start*2)
    {
      printMatrixInCircle(matrix, result, start);
      ++start;
    }

    return result;
  }

  void printMatrixInCircle(vector<vector<int>> &matrix, vector<int> &result, int start)
  {
    int localrow = matrix.size()-1 - start;
    int localcol = matrix[0].size()-1 - start;
    int val = 0;
    //从左到右
    for(int i=start; i<=localcol; ++i)
    {
      val = matrix[start][i];
      result.push_back(val);
    }

    //从下往上,首先判断有下的条件
    if(start < localrow)
    {
      for(int i=start+1; i<=localrow; ++i)
      {
        val = matrix[localcol][i];
        result.push_back(val);
      }
    }

    //从右往左,首先判断有右的条件
    if(start < localrow && start < localcol)
    {
      for(int i=localcol-1; i>=start; --i)
      {
        val = matrix[localrow][start];
        result.push_back(val);
      }
    }

    //从下往上
    if(start < localrow-1 && start < localcol)
    {
      for(int i=localrow-1; i>=start+1; --i)
      {
        val = matrix[i][start];
        result.push_back(val);
      }
    }

    return;
  }

};

 

posted @ 2017-02-28 21:54  夜雨寒山  阅读(182)  评论(0编辑  收藏  举报