顺时钟方向螺旋状打印矩阵元素
前一阵在bbs上看到的一道面试题,今日闲来无事,就写了个小小程序试了一下。
想法就是先计算要打印的行数和列数的总和(totalSteps),然后很容易就会发现
totalSteps % 4 = 0 从左到右打印最上面一行元素 (己打印的除外)
totalSteps % 4 = 1 从上到下打印最右面一列元素
totalSteps % 4 = 2 从右到左打印最下面一行元素
totalSteps % 4 = 3 从下到上打印最左面一列元素
有了上面的想法,程序就很简单了,维护四个变量(当前最小行 lowd,最大行 highd,最小列lowr,最大列 highr),一个for循环从0开始到totalSteps就ok了。
程序如下:
想法就是先计算要打印的行数和列数的总和(totalSteps),然后很容易就会发现
totalSteps % 4 = 0 从左到右打印最上面一行元素 (己打印的除外)
totalSteps % 4 = 1 从上到下打印最右面一列元素
totalSteps % 4 = 2 从右到左打印最下面一行元素
totalSteps % 4 = 3 从下到上打印最左面一列元素
有了上面的想法,程序就很简单了,维护四个变量(当前最小行 lowd,最大行 highd,最小列lowr,最大列 highr),一个for循环从0开始到totalSteps就ok了。
程序如下:
#include <iostream>
using namespace std;
void Process2DSpire(int *a,int n,int m)
{
int totalSteps = 2*n-1;
int lowd ,lowr;
lowd = lowr = 0;
int highd = n-1;
int highr = m-1;
for(int step = 0; step<totalSteps; step++)
{
switch( step%4)
{
case 0:
for(int i = lowr; i<=highr;++i)
cout<<a[lowd*m+i]<<" ";
++lowd;
break;
case 1:
for(int i = lowd;i<=highd;++i)
cout<<a[i*m+highr]<<" ";
--highr;
break;
case 2:
for(int i=highr;i>=lowr;--i)
cout<<a[highd*m+i]<<" ";
--highd;
break;
case 3:
for(int i = highd;i>=lowd;--i)
cout<<a[i*m+lowr]<<" ";
lowr++;
break;
default:
break;
}
}
}
int main()
{
//int Rectangle[3][5] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
int Rectangle[3][2] = {{1,2},{3,4},{5,6}};
//Process2DSpire(&Rectangle[0][0],3,5);
Process2DSpire(&Rectangle[0][0],3,2);
return 0;
}
using namespace std;
void Process2DSpire(int *a,int n,int m)
{
int totalSteps = 2*n-1;
int lowd ,lowr;
lowd = lowr = 0;
int highd = n-1;
int highr = m-1;
for(int step = 0; step<totalSteps; step++)
{
switch( step%4)
{
case 0:
for(int i = lowr; i<=highr;++i)
cout<<a[lowd*m+i]<<" ";
++lowd;
break;
case 1:
for(int i = lowd;i<=highd;++i)
cout<<a[i*m+highr]<<" ";
--highr;
break;
case 2:
for(int i=highr;i>=lowr;--i)
cout<<a[highd*m+i]<<" ";
--highd;
break;
case 3:
for(int i = highd;i>=lowd;--i)
cout<<a[i*m+lowr]<<" ";
lowr++;
break;
default:
break;
}
}
}
int main()
{
//int Rectangle[3][5] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
int Rectangle[3][2] = {{1,2},{3,4},{5,6}};
//Process2DSpire(&Rectangle[0][0],3,5);
Process2DSpire(&Rectangle[0][0],3,2);
return 0;
}