给定一个整形矩阵matrix,请按照顺时针的方向打印矩阵
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
额外空间复杂度:O(1)
#include <iostream>
#include<stdlib.h>
void PrintMatrix(int matrix[][4], int left, int right, int top, int bottom);
void RotateMatrix(int matrix[][4],int left, int right, int top, int bottom);
using namespace std;
int main()
{
int matrix[][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int left=0;
int top=0;
size_t right=sizeof(matrix[0])/sizeof(matrix[0][0])-1;
size_t bottom=sizeof(matrix)/sizeof(matrix[0])-1;
RotateMatrix(matrix,left,right,top,bottom);
PrintMatrix(matrix, left,right,top,bottom);
return 0;
}
void PrintMatrix(int matrix[][4], int left, int right, int top, int bottom)
{
while(left<=right && top<=bottom)
{
int i,j;
for(j=left; j<=right; j++) cout<<matrix[top][j]<<" ";
top++;
for(i=top; i<=bottom; i++) cout<<matrix[i][right]<<" ";
right--;
for(j=right; j>=left ;j--) cout<<matrix[bottom][j]<<" ";
bottom--;
for(i=bottom; i>=top; i--) cout<<matrix[i][left]<<" ";
left++;
}
return;
}
void RotateMatrix(int matrix[][4],int left, int right, int top, int bottom)
{
while(left<right && top<bottom)
{
int tmp;
for(int i=left; i<right; i++)
{
tmp=matrix[top][left+i];
matrix[top][left+i]=matrix[bottom-i][left];
matrix[bottom-i][left]=matrix[bottom][right-i];
matrix[bottom][right-i]=matrix[top+i][right];
matrix[top+i][right]=tmp;
}
left++;
right--;
top++;
bottom--;
}
return;
}
在进行90度旋转的时候,for循环中i的取值范围为(left,right-1),进了这个坑好长时间才爬出来。。。。
“之”字形打印矩阵:
给定一个矩阵matrix,按照“之”字形的方式打印这个矩阵,例如:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
输出结果为:1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16
方法思路:
1.上坐标(topR,topC)初始化为(0,0),先沿着矩阵第一行移动(topC++),当到达第一行最右边的元素后,再沿着矩阵最后一列移动(topR++)
2.下坐标(bottomR,bottomC)初始化为(0,0),先沿着矩阵的第一列移动(bottom++),当到达第一列的最下边的元素时,在沿着矩阵最后一行移动(bottomC++)
3.上坐标与下坐标同步移动,每次移动后的上坐标与下坐标的连线就是矩阵中的一条斜线,打印斜线上的元素即可。
4.如果上次斜线是从左下向右上,这次则从右上向左下打印,反之亦然。
void PrintMatrixZig(int matrix[][4], int left, int right,int top,int bottom)
{
int topR=0;
int topC=0;
int bottomR=0;
int bottomC=0;
int endR=bottom;
int endC=right;
bool fromUp=false;
while(topR != endR+1)
{
printlevel(matrix,topR,topC,bottomR,bottomC,fromUp);
if(topC==endC)
{
topR=topR+1;
}
else
{
topC=topC+1;
}
if(bottomR==endR)
{
bottomC = bottomC+1;
}
else
{
bottomR=bottomR+1;
}
fromUp = !fromUp;
}
return ;
}
void printlevel(int matrix[][4], int topR, int topC, int bottomR, int bottomC, bool f)
{
if(f)
{
while(topR!=bottomR+1)
{
cout<<matrix[topR++][topC--]<<" ";
}
}
else
{
while(bottomR!=topR-1)
{
cout<<matrix[bottomR--][bottomC++]<<" ";
}
}
}