顺时针打印矩阵

来源:互联网 发布:龙刀皮肤淘宝上多少钱 编辑:程序博客网 时间:2024/06/06 20:58

设置四个变量left ,right,top,bottom分别存储左右上下的界限,循环打印,

注意:当打印最后一行或者一列的时候,不能重复打印,所以下面代码的if (top != bottom)//从右到左时 if (left != right)//从下到上时的判断很重要。


代码:

vector<int> printMatrix(vector<vector<int> > matrix) {


        vector<int> result;
        int m=matrix.size();//行数
        if(m==0)
            return result;
        int n=matrix[0].size();//列数
        if(n==0)
            return result;

        int left=0,right=n-1,top=0,bottom=m-1;
        
        while(left<=right && top<=bottom)
        {             
            for (int i = left; i <= right; ++i)//从左到右
                result.push_back(matrix[top][i]);
            
            for (int i = top + 1; i <= bottom; ++i)//从上到下
                result.push_back(matrix[i][right]);
            
            if (top != bottom)//从右到左
            for (int i = right - 1; i >= left; --i)
                result.push_back(matrix[bottom][i]);
            
            if (left != right)//从下到上
            for (int i = bottom - 1; i > top; --i)
                result.push_back(matrix[i][left]);
                
            left++,top++,right--,bottom--;
        }
        return result;

    }


1 0
原创粉丝点击