题目:
给定一个矩阵matrix,按照“之”字形的方式打印这个矩阵。例如:
1 2 3 4
5 6 7 8
9 10 11 12
“之”字形打印的结果为:1,2,5,9,6,3,4,7,10,11,8,12
要求额外的空间复杂度为O(1)。
解题思路:
上坐标(tR,tC)的初始为(0,0),先沿着矩阵的第一行移动(tC++),当达到第一行最右边的元素后,再沿着矩阵最后一列移动 (tR++)。
下坐标(dR,dC)的初始为(0,0),先沿着矩阵的第一列移动(dR++),当到达第一列最下边的元素时,再沿着矩阵的最后一行一定(dC++)。
上坐标与下坐标同步移动,每次移动后的上坐标与下坐标的连线就是矩阵中的一条斜线,打印斜线上的元素即可。
如果上次斜线是从左下向右上打印的,这次一定是从右上向左下打印,反之亦然。总之,可以把打印的方向用boolean变量表示,每次取反即可。
代码如下:
#include<iostReam>
using namespace std;
void Print(int(*a)[4], int tR, int tC, int dR, int dC, bool flag);
void PrintMatRix()
{
int arr[][4] = { { 1, 2, 3, 4 }
, { 5, 6, 7, 8 }
, {9,10,11,12}
};
int tC = 0;
int tR = 0;
int dC = 0;
int dR = 0;
int endR = 2;
int endC = 3;
bool fromup = false;
while (tR != endR + 1)
{
Print(arr, tR, tC, dR, dC, fromup);
tR = tC == endC ? tR + 1 : tR;
tC = tC == endC ? tC : tC + 1;
dC = dR == endR ? dC + 1 : dC;
dR = dR == endR ? dR : dR + 1;
fromup = !fromup;
}
}
void Print(int (*a)[4] ,int tR, int tC, int dR, int dC ,bool flag)
{
if (flag)
{
while (tR != dR + 1)
cout << a[tR++][tC--] << " ";
}
else
{
while (dR != tR - 1)
{
cout << a[dR--][dC++] << " ";
}
}
}
int main()
{
PrintMatRix();
system("pause");
}
拓展:
循环转圈打印数组:
代码如下:
#include<iostream>
using namespace std;
void PrintEadge(int *arr, int tR, int tC, int dR, int dC,int rows,int cols)
{
//当子矩阵只有一行时
if (tR == dR)
{
for (int i = tC; i < dC; i++)
{
cout << arr[tR*rows+i] << " ";
}
cout << endl;
}
//当子矩阵只有一列时
else if (tC == dC)
{
for (int i = tR; i < dR; i++)
{
cout << arr[i*rows+dC] << " ";
}
cout << endl;
}
//一般情况
else
{
int curC = tC;
int curR = tR;
while (curC != dC)
{
cout << arr[tR*rows+curC] << " ";
curC++;
}
cout << endl;
while (curR != dR)
{
cout << arr[curR*rows+dC]<<" ";
curR++;
}
cout << endl;
while (curC != tC)
{
cout << arr[dR*rows+curC] << " ";
curC--;
}
cout << endl;
while (curR != tR)
{
cout << arr[curR*rows+tC] << " ";
curR--;
}
cout << endl;
}
}
void PrintCircle(int *arr, int rows, int cols)
{
int tR = 0;
int tC = 0;
int dR = rows - 1;
int dC = cols - 1;
while (tR <= dR&&tC <= dC)
{
PrintEadge(arr, tR++, tC++, dR--, dC--,rows,cols);
}
}
int main()
{
int arr[4][4] = { { 1, 2, 3, 4 }
, { 5, 6, 7, 8 }
, { 9, 10, 11, 12 }
, { 13, 14, 15, 16 }
};
PrintCircle((int*)arr, 4, 4);
cout << endl;
system("pause");
}