码迷,mamicode.com
首页 > 其他好文 > 详细

顺时针打印

时间:2016-06-21 22:42:29      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.*/
class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        int up,down,left,right;
        vector<int> result;
        int row = matrix.size();
        if(row == 0) return result;
        int col = matrix[0].size();
        up = left = 0;
        right = col-1;
        down = row -1;
        int sig = 1;
        //right = down = matrix.size()-1;
        while((up<=down)&&(left<=right)){
            if(sig ==1){
                for(int i = left;i<=right;i++){
                result.push_back(matrix[up][i]);
            }
            up++;
            sig=2;
                
            }else if(sig ==2){
                for(int j =up;j<=down;j++){
                result.push_back(matrix[j][right]);
            }
            right--;
            sig=3;
                
            }else if(sig ==3){
                for(int i = right;i>=left;i--){
                result.push_back(matrix[down][i]);
            }
            down--;
            sig=4;
            }else if (sig ==4){
                for(int j =down;j>=up;j--){
                result.push_back(matrix[j][left]);
            }
            left++;
            sig=1;
            }
    
        }
              if(up<=down){
                  if(sig==4){
                      for(int j = down;j>=up;j--){
                          result.push_back(matrix[j][left]);
                      }
                      
                  }else if(sig ==2){
                      for(int j =up;j<=down;j++){
                            result.push_back(matrix[j][right]);
                      }
                      
                  }
                if(left<=right){
                   if(sig ==1 ){
                      for(int i = left;i<=right;i++){
                          result.push_back(matrix[up][i]);
                            }
                   }else if(sig == 3){
                      for(int i = right;i>=left;i--){
                          result.push_back(matrix[down][i]);
                          }
                      }
                  }
                  
              }
        return result;

    }
};

 

顺时针打印

标签:

原文地址:http://www.cnblogs.com/mokayy/p/5605161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!