首页 > 试题广场 >

顺时针打印矩阵

[编程题]顺时针打印矩阵
  • 热度指数:21935 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。

给定int矩阵mat,以及它的维数nxm,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。

测试样例:
[[1,2],[3,4]],2,2
返回:[1,2,4,3]
     importjava.util.*;  
        
     publicclassPrinter {  
         publicint[]    clockwisePrint(int[][] mat,intn,intm) {  
           int[] a =newint[m*n];  
             if( mat ==null)  
                 returna;  
             inti =0;  
             intj =0;  
             intk =0;  
             intstartX =0;  
             intstartY =0;     
             intendX = n -1;  
             intendY = m -1;  
             while( startX <=    endX && startY <= endY ){  
         
             //如果只剩下一行
  
                 if( startX ==    endX ){    
  
                     for( ; j    <= endY ;j++,k++){  
                         a[k] =    mat[startX][j];  
                     }  
                     returna;  
                 }  
             //如果只剩下一列  
                 if( startY ==    endY ){  
                     for( ; i    <= endX ; i++,k++){  
                         a[k] =    mat[i][startY];  
                     }  
                     returna;  
                 }  
                 
                 //将矩阵上边除右顶点添加到返回的数组中
  
                 for( ; j <    endY ; j++,k++){  
                     a[k] =    mat[i][j];  
                 }  
                //将矩阵右边除边下顶点添加到返回的数组中  
                 for( ; i <    endX ; i++,k++){  
                     a[k] =    mat[i][j];  
                 }  
               //将矩阵下边除边左顶点添加到返回的数组中  
                 for( ; j >    startX ; j--,k++){  
                     a[k] =    mat[i][j];  
                 }  
                  //将矩阵左边除边上顶点添加到返回的数组中  
                 for( ; i >    startY ; i--,k++){  
                     a[k] =    mat[i][j];  
                 }  
                    
                 i++;  
                 j++;  
                 startX++;  
                 startY++;  
                 endX--;  
                 endY--;  
             }        
        
             returna;  
                
         }  
     }  

      
编辑于 2016-03-11 22:18:27 回复(7)
class Printer {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
        vector<int>ans;
        int order[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//方向数组
        int i=0,j=-1,start = 0;
        while (true) {
            int a = i+order[start][0],b=j+order[start][1];
            if(!(0<=a&&a<n)||!(0<=b&&b<m)||mat[a][b]==INT_MAX)
                start = (start+1)%4;
            i=i+order[start][0],j=j+order[start][1];
            ans.push_back(mat[i][j]);
            mat[i][j] = INT_MAX;
            if(ans.size()==n*m)
                break;
        }
        return ans;
    }
};

发表于 2016-04-11 11:34:21 回复(3)
ret = []
while len(mat) > 0:
	ret += mat[0] #将矩阵的首行放入 ret
	mat = [x for x in zip(*mat[1:])][::-1] #去掉矩阵首行后逆时针旋转90度
return ret
编辑于 2016-10-02 01:21:04 回复(6)

python解法:

class Printer:
    def clockwisePrint(self, mat, n, m):
        res = []
        while mat:
            res += mat.pop(0)
            if mat and mat[0]:
                for row in mat:
                    res.append(row.pop())
            if mat:
                res += mat.pop()[::-1]
            if mat and mat[0]:
                for row in mat[::-1]:
                    res.append(row.pop(0))
        return res
编辑于 2017-09-12 11:57:19 回复(1)
class Printer {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
        // write code here
       vector<int> ret;
       int x1 = 0, y1 = 0;      //左上角坐标
       int x2 = n-1, y2 = m-1;  //右下角坐标
       while(x1 <= x2 && y1 <= y2){
           for(int j = y1; j <= y2; ++j) 
               ret.push_back(mat[x1][j]);
           for(int i = x1+1; i < x2; ++i)
               ret.push_back(mat[i][y2]);
           for(int j = y2; x1 < x2 && j >= y1; --j) //x1 < x2:只有在不是单一的横行时才执行这个循环
               ret.push_back(mat[x2][j]);
           for(int i = x2-1; y1 < y2 && i > x1; --i)//y1 < y2:只有在不是单一的竖列时才执行这个循环
               ret.push_back(mat[i][y1]);
           x1++; y1++;
           x2--; y2--;
       }
       return ret;
    }
};

发表于 2017-07-01 15:19:35 回复(0)
从左至右,从上至下,从右至左,从下至上循环打印就好
class Printer {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) 
    {
        // write code here
        vector<int> res;
        int colbegin=0,colend=m-1,rowbegin=0,rowend=n-1;
        int i=0,j=0;
        while(colbegin<=colend && rowbegin<=rowend)
        {
        	for(j=colbegin;j<=colend;j++)//right
            	res.push_back(mat[i][j]);
        	j--;rowbegin++;
            if(res.size()>=n*m) return res;
        	for(i=rowbegin;i<=rowend;i++)//down
            	res.push_back(mat[i][j]);
        	i--;colend--;
            if(res.size()>=n*m) return res;
        	for(j=colend;j>=colbegin;j--)//left
            	res.push_back(mat[i][j]);
        	j++;rowend--;
            if(res.size()>=n*m) return res;
        	for(i=rowend;i>=rowbegin;i--)
            	res.push_back(mat[i][j]);
        	i++;colbegin++;
            if(res.size()>=n*m) return res;
        } 
        return res;
    }
};

发表于 2017-05-20 11:07:23 回复(0)
PnP头像 PnP
为什么没人用Python?
class Printer:

    # 返回循环次数
    def iteration_num(self, n, m):
        if(n <= m):
            return n + (n - 1)
        else:
            return 2 * m

    def clockwisePrint(self, mat, n, m):
        l = []
        for i in range(self.iteration_num(n,m)):
            t = i / 4
            if(i%4==0):
                for j in range(0+t,m-t):
                    l.append(mat[0+t][j])
            if(i%4==1):
                for j in range(1+t,n-t):
                    l.append(mat[j][m-1-t])
            if(i%4==2):
                for j in range(m-2-t,-1+t,-1):
                    l.append(mat[n-1-t][j])
            if(i%4==3):
                for j in range(n-2-t,0+t,-1):
                    l.append(mat[j][0+t])
        return l

编辑于 2016-05-02 05:32:11 回复(0)
classPrinter {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, intn, intm) {
         
 
        // write code here
        intstart=0;
        vector<int> imat;
         
        while(n>start*2&& m>start*2){
            intendX=m-1-start;
            intendY=n-1-start;
            //左-》右
            for(inti=start;i<=endX;++i)
                imat.push_back(mat[start][i]);
 
            //上-》下
            if(start<endY){
                for(inti=start+1;i<=endY;++i)
                    imat.push_back(mat[i][endX]);  
            }
 
            //右-》左
            if(start<endX&&start<endY){
                for(inti=endX-1;i>=start;--i)
                    imat.push_back(mat[endY][i]);
            }
            //下-》上
            if(start<endX&&start<endY-1){
                for(inti=endY-1;i>=start+1;--i)
                    imat.push_back(mat[i][start]);
            }
            ++start;
        }
        returnimat;
    }
     
};

发表于 2015-09-12 10:11:00 回复(2)
采用统一的格式,cnt代表循环的圈数。
class Printer {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
        // write code here
        vector<int> res;
        if(n==0 || m==0)    return res;
        int cnt=0,row=0,col=0;
        while(res.size()<n*m)
        {
            while(col<m-cnt && res.size()<n*m)
                res.push_back(mat[row][col++]);
            col--,row++;
            if(res.size()>=n*m)    break;
            
            while(row<n-cnt && res.size()<n*m)
                res.push_back(mat[row++][col]);
            row--,col--;
            if(res.size()>=n*m)    break;
            
            while(col>=cnt && res.size()<n*m)
                res.push_back(mat[row][col--]);
            col++,row--;
            if(res.size()>=n*m)    break;
            
            while(row>cnt && res.size()<n*m)
                res.push_back(mat[row--][col]);
            row++,col++;
            if(res.size()>=n*m)    break;
            cnt++;
        }
        return res;
    }
};


编辑于 2020-08-24 11:01:22 回复(0)
class Printer {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
        // write code here
    int row = 0, col = 0;
    int rrow = n - 1 , ccol = m - 1;
    vector<int> arr;
    while (1)
    {
        for (int i = col; i <= ccol; i++)
            arr.push_back(mat[row][i]);
        row++;
        if (arr.size()==n*m)
            break;
        for (int i = row; i <= rrow; i++)
            arr.push_back(mat[i][ccol]);
        ccol--;
        if (arr.size()==n*m)
            break;
        for (int i = ccol; i >= col; i--)
            arr.push_back(mat[rrow][i]);
        rrow--;
        if (arr.size()==n*m)
            break;
        for (int i = rrow; i >= row; i--)
            arr.push_back(mat[i][col]);
        col++;
        if (arr.size()==n*m)
            break;
    }
    return arr;
    }
};
发表于 2020-04-27 00:21:27 回复(0)
import java.util.*;

public class Printer {
    public int[] clockwisePrint(int[][] mat, int n, int m) {
        // write code here
        int[] a=new int[n*m];
        int index=0;
        int topX=0, topY=0, lowX=n-1, lowY=m-1;
        while(topX<=lowX && topY<=lowY){
            if(topX==lowX){    //只剩下一行时
                for(int i=topY; i<=lowY; i++)
                    a[index++]=mat[topX][i];
                return a;
            }
            if(topY==lowY){  //只剩下一列时
                for(int i=topX; i<=lowX; i++)
                    a[index++]=mat[i][topY];
                return a;
            }
            for(int i=topY; i<lowY; i++)
                a[index++]=mat[topX][i];
            for(int i=topX; i<lowX; i++)
                a[index++]=mat[i][lowY];
            for(int i=lowY; i>topY; i--)
                a[index++]=mat[lowX][i];
            for(int i=lowX; i>topX; i--)
                a[index++]=mat[i][topY];
            topX++; topY++; lowX--; lowY--;
        }
        return a;
    }
}

发表于 2018-06-28 21:35:07 回复(1)

public int[] clockwisePrint(int[][] mat, int n, int m) {

    int tR = 0;
    int tC = 0;
    int dR = n - 1;
    int dC = m - 1;
    int index = 0;
    int[] res = new int[n * m];
    while (tR <= dR && tC <= dC) {
        if (tR == dR) {// 只有一行的时候
            for (int i = tC; i <= dC; i++) {
                res[index++] = mat[tR][i];
            }
        } else if (tC == dC) {// 只有一列的时候
            for (int i = tR; i <= dR; i++) {
                res[index++] = mat[i][tC];
            }
        } else {
            int curC = tC;
            int curR = tR;
            while (curC != dC) {// 从左到右打印
                res[index++] = mat[tR][curC];
                curC++;
            }
            while (curR != dR) {// 从上往下打印
                res[index++] = mat[curR][dC];
                curR++;
            }
            while (curC != tC) {// 从右往左打印
                res[index++] = mat[dR][curC];
                curC--;
            }
            while (curR != tR) {// 从下往上打印
                res[index++] = mat[curR][tC];
                curR--;
            }
        }
        tR++;
        tC++;
        dR--;
        dC--;

    }
    System.out.println(Arrays.toString(res));
    return res;
}
发表于 2018-03-13 17:45:51 回复(1)
class Printer {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
        vector<int> r;
        int left=0,right=m-1,top=0,bottom=n-1;
        int i=0,j=0,k=0;
        while(k<m*n)
        {             for(i=top,j=left;j<=right;j++)                 r.push_back(mat[i][j]), k++;             top++;             if(k==m*n)                 break;             for(j=right,i=top;i<=bottom;i++)                 r.push_back(mat[i][j]), k++;             right--;             if(k==m*n)                 break;                              for(i=bottom,j=right;j>=left;j--)                 r.push_back(mat[i][j]), k++;             bottom--;             if(k==m*n)                 break;                              for(j=left,i=bottom;i>=top;i--)                 r.push_back(mat[i][j]), k++;             left++;             if(k==m*n)                 break;         }         return r;
    }
};


发表于 2017-12-04 18:51:03 回复(0)
import java.util.*;

public class Printer {
    public int[] clockwisePrint(int[][] mat, int n, int m) {
        int i=0;
        int j=0;
        int lmin=0;
        int rmin=0;
        int lmax=n-1;
        int rmax=m-1;
        int[] p = new int[n*m];
        
        for(int count=0;count<n*m;count++){
            p[count]=mat[i][j];
            if(i==lmin&&j<rmax){
                j++;
            }
            else if(i<lmax&&j==rmax){
                i++;
            }
            else if(i==lmax&&j>rmin){
                j--;
            }
            else if(i>lmin&&j==rmin){
                i--;
            }
            if(i==lmin&&j==rmin){
                lmin++;
                rmin++;
                lmax--;
                rmax--;
                i=lmin;
                j=rmin;
            }
        }
        return p;
    }
}
发表于 2017-01-24 22:46:14 回复(0)

classPrinter {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, intn, intm) {
        // write code here
        vector<int> matrix;
        inttR=0;
        inttC=0;
        intdR=n-1;
        intdC=m-1;
        while(tR<=dR && tC<=dC){
            intj;
            if(tR==dR){
                for(j=tC;j<=dC;j++){
                    matrix.push_back(mat[tR][j]);
                     
                }
            }elseif(tC==dC){
                for(j=tR;j<=dR;j++){
                    matrix.push_back(mat[j][tC]);
                }
            }else{
                intcurC=tC;
                intcurR=tR;
                while(curC != dC){
                    matrix.push_back(mat[tR][curC]);
                    curC++;
                }
                while(curR != dR){
                    matrix.push_back(mat[curR][dC]);
                    curR++;
                }
                while(curC != tC){
                    matrix.push_back(mat[dR][curC]);
                    curC--;
                }
                while(curR != tR){
                    matrix.push_back(mat[curR][tC]);
                    curR--;
                }
                 
            }
            tR++;
            tC++;
            dR--;
            dC--;
        }
        returnmatrix;
    }
};

发表于 2017-01-12 16:15:10 回复(0)
class Printer {
public:
vector<int> clockwisePrint(vector<vector<int>> mat, int n, int m) 
{
// write code here
vector<int>result;

int left = 0;
int top = 0;
int right = m-1;
int bottom = n-1;

int x=0;
int y=0;
while(left<=right && top<=bottom)
{
for(x = left;x<=right;x++)
{
result.push_back(mat[top][x]);
}
top++;
if(top>bottom)
{
break;
}

for(y = top;y<=bottom;y++)
{
result.push_back(mat[y][right]);
}
right--;
if(right<left)
{
break;
}

for(x = right;x>=left;x--)
{
result.push_back(mat[bottom][x]);  
}
bottom--;
if(bottom<top)
{
break;
}

for(y = bottom;y>=top;y--)
{
result.push_back(mat[y][left]);
}
left++; 
if(left>right)
{
break;
}
}

return result;
}
};
发表于 2016-09-06 10:42:13 回复(0)
import java.util.*;

public class Printer {
    public int[] clockwisePrint(int[][] mat, int n, int m) {
        int startX = 0, endX = n - 1;
        int startY = 0, endY = m - 1;
        int[] res = new int[n * m];
        int k = 0;
        while (true) {
            for (int i = startY; i <= endY; i++) {
                res[k++] = mat[startX][i];
            }
            startX++;
            if (startX > endX) {
                break;
            }
            for (int i = startX; i <= endX; i++) {
                res[k++] = mat[i][endY];
            }
            endY--;
            if (startY > endY) {
                break;
            }
            for (int i = endY; i >= startY; i--) {
                res[k++] = mat[endX][i];
            }
            endX--;
            if (startX > endX) {
                break;
            }
            for (int i = endX; i >= startX; i--) {
                res[k++] = mat[i][startY];
            }
            startY++;
            if (startY > endY) {
                break;
            }
        }
        return res;
    }
}

发表于 2016-08-28 09:42:57 回复(0)
class Printer {
public:
    void print(vector<vector<int> > mat,vector<int> &vec, pair<int,int> point1,pair<int,int> point2){
        for(int i=point1.second;i<=point2.second;i++)
            vec.push_back(mat[point1.first][i]);
        for(int i=point1.first+1;i<=point2.first;i++)
            vec.push_back(mat[i][point2.second]);
        for(int i=point2.second-1;i>=point1.second&&point1.first!=point2.first;i--)
            vec.push_back(mat[point2.first][i]);
        for(int i=point2.first-1;i>point1.first&&point1.second!=point2.second;i--)
            vec.push_back(mat[i][point1.second]);
    }
    vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
        vector<int> vec;
        int i=0;
        while(2*i<=n-1&&2*i<=m-1){
            print(mat,vec,pair<int,int>(i,i),pair<int,int>(n-1-i,m-1-i));
            i++;
        }
       	return vec;            
    }
};

发表于 2016-08-27 16:08:17 回复(0)
class Printer {
	vector<int> vc;
public:
	void printCircle(vector<vector<int> > mat,int x1, int y1,int x2,int y2)  //定义一个打印一圈的函数
	{
		if (x1==x2&&y1==y2)
		{
			vc.push_back(mat[x1][y1]);
			return;
		}
		else if (x1==x2&&y1!=y2)
		{
			for (int y = y1; y <= y2;y++)
			{
				vc.push_back(mat[x1][y]);
			}
			return;   //跳出函数,不然可能继续执行下面的函数,重读数据。
		}
		else if (y1==y2&&x1!=x2)
		{
			for (int x = x1; x <= x2;x++)
			{
				vc.push_back(mat[x][y1]);
			}
			return;
		}
		for (int y = y1; y < y2;y++)
		{
			vc.push_back(mat[x1][y]);
		}
		for (int x = x1; x < x2;x++)
		{
			vc.push_back(mat[x][y2]);
		}
		for (int y= y2; y>y1;y--)
		{
			vc.push_back(mat[x2][y]);
		}
		for (int x = x2; x > x1;x--)
		{
			vc.push_back(mat[x][y1]);
		}
	}
vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
		// write code here
		int startX = 0, startY = 0;
		int endX = n - 1, endY = m - 1;
		while (startX <= endX&&startY <= endY)
		{
			printCircle(mat, startX, startY, endX, endY);
			startX++;
			startY++;
			endX--;
			endY--;
		}
		return vc;
	}
}

编辑于 2016-06-27 18:21:50 回复(0)
import java.util.*;
public class Printer {
    int t = 0;
    public int[] clockwisePrint(int[][] mat, int n, int m) {
        // write code here
        int a[] = new int[m*n];
      
        int start = 0;
        while(n>start*2&&m>start*2)
            {
         print(mat,n,m,start,a);
            start++;
        }
        return a;
        
    }
    public void print(int[][] mat, int n, int m,int start,int a[]){
        int endx = n-1-start;//
        int endy = m-1-start;
         
       
        for(int i = start;i<=endy;i++)
            {
            a[t++]  = mat[start][i];
            
        }
        if(start<endx)
            {
            for(int i = start+1;i <=endx;i++ )
                  a[t++] = mat[i][endy];
        }
        if(start<endy&&start<endx)
            {
            for(int i= endy-1;i>=start;i--)
                 a[t++]  = mat[endx][i];
        }
        if(start<endx-1&&start<endy)
            {
            for(int i = endx-1;i>=start+1;i--)
                  a[t++]  = mat[i][start];
        }
 
    }
   
}

发表于 2016-04-26 21:42:56 回复(0)

问题信息

难度:
130条回答 29261浏览

热门推荐

通过挑战的用户

查看代码
顺时针打印矩阵