troubleasy

导航

 

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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.

    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int>number;
        if(matrix.empty()) return number;
        int row=matrix.size(),col=matrix[0].size();
        int n=0;
        int s;
        if(row<=col)
        {s=(row%2?(row/2+1):row/2);
        }else
        {
        s=(col%2?(col/2+1):col/2);

        }
        while(n<s)
        {
            //上右下左
            //上

           // cout<<"nnnn:   "<<s<<"   "<<n<<endl;
                for(int i=n;i<col-n;i++)
                    number.push_back(matrix[n][i]);
                //右
               for(int i=n+1;i<row-n;i++)
                    number.push_back(matrix[i][col-1-n]);
                //xia
              // for(int i=n;i<row-1-n;i++)
                for(int i=col-2-n;i>=n&&(row-1-n!=n);i--)
                    number.push_back(matrix[row-1-n][i]);
                //zuo
                //for(int i=n+1;i<row-1-n;i++)
                    for(int i=row-2-n;i>=n+1&&(n!=col-1-n);i--)
                    number.push_back(matrix[i][n]);
                    n++;
                //单行单列需考虑
                   
                
            
        }
           return number;
    }

posted on 2020-05-26 15:05  troubleasy  阅读(118)  评论(0编辑  收藏  举报