今天的一道笔试题,感觉不难,但没做好,这里研究一下。
蛇形遍历
要求 有一个二维数组,请按蛇形遍历输出该矩阵
例如:下图的3*4 矩阵
其输出是:
1 2 5 9 6 3 4 7 10 11 8 12
这是 列数大于行数的情况:
还有列数=行数的情况
其输出是:
1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16
和 列数小于行数的情况
其输出是:
1 2 4 7 5 3 6 8 10 11 9 12
解题思路
通过观察可知:只有4个操作
为 向左移动定义为first()
左斜下移动 定义为second()
为 向下移动 定义为third()
为 右斜向上移动定义为 four()
对矩阵做反对角线 向这样:
M
M=N
M>N
可以看出在对角线上方的操作为:
其规律可推为 1次first 1次 second 1次third 2次four
1次first 3次 second 1次third 4次four
1次first 5次 second 1次third 6次four
First 和third每次次数不变而 second 和 four 依次递增
可以看出在对角线下方的操作为:
其规律可推为 1次first 6次four 1次third 5次second
1次first 4次four 1次third 3次second
1次first 2次four 1次third 1次second
First 和third每次次数不变而 second 和 four 依次递减
罗列C代码如下:
#include
using namespace std;
#define NULL 0
#define aa m44
int m34[3][4]={ {1, 2, 3, 4},
{5, 6, 7, 8},
{9,10,11,12}
};
int m44[4][4]={ { 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9,10,11,12},
{13,14,15,16}
};
int m43[4][3]={ { 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9},
{10,11,12}
};
int first(int *x,int *y,int m,int n)
{
if (*y < n-1)
{
++(*y);
cout< return 1;
}
return 0;
}
void second(int *x,int *y,int m,int n,int count)
{
while(count>0 && *x=1)
{
++(*x);
--(*y);
cout<0 && *x>=1 && *y cout<=n )break;
}
if (m<=n) --add;
else ++add;
while(!(curY==n-1 && curX==m-1))
{
if (first(&curX,&curY, m, n)){
--add;
four(&curX,&curY, m, n,add);
}
if (third(&curX,&curY, m, n)){
--add;
second(&curX,&curY, m, n,add);
}
/* cout<>u;
return 0;
}
对3*4矩阵的结果为:
对4*4矩阵的结果为:
对4*3的结果为:
时间复杂度当然是O(M*N) 即二维矩阵的个数。