您的位置:首页 > 编程语言 > C语言/C++

菜鸟系列之C/C++经典试题(十一)

2014-09-08 19:50 274 查看
顺时针打印矩阵
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

例如:如果输入如下矩阵:

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。

分析:第一次看到这个题目的时候,觉得这个题目很简单,完全不需要用到数据结构或者算法的知识,因此没有兴趣做这道题。后来听到包括Autodesk、EMC在内的多家公司在面试或者笔试里采用过这道题,于是想这么多家公司用它来检验一个程序员的编程功底总是有原因的,于是决定自己写一遍试一下。真正写一遍才发现,要完整写出这道题的代码,还真不是件容易的事情。

我实现的思路就是一个一个边的打印,打印顺序上下左右,打印完了之后, 有可以进行下一次的打印了, 通过画图, 我们可以很容易发现, 比如是5x5的矩阵,第一次打印得边的宽度应该是4,第二个打印的变得比原来少2,别忘了当宽度为奇数的时候,最后剩下一个最后一个元素哦。在这里我给出了两种实现,递归的和非递归的。参考代码如下:

inline void printOne(const int val)
{
static int count = 0;
printf("%-4d", val);

if (++count == 10)
{
cout << endl;
count = 0;
}
}

void printClockwiseRecursive(const int *src, const int width, const int cur)
{
// print the last one element
if (0 == cur)
{
printOne(*src);
return;
}

// print the up
for (register int i = 0; i < cur; ++i)
{
printOne(*src++);
}

// print the right
for (register int i = 0; i < cur; ++i)
{
printOne(*src);
src += width;
}

// print the bottom
for (register int i = cur; i > 0; --i)
{
printOne(*src--);
}

// for the left
for (register int i = cur; i > 0; --i)
{
printOne(*src);
src -= width;
}

if (cur >= 2)
{
printClockwiseRecursive(src + width + 1, width, cur - 2);
}
}

void printClockwise(const int *src, const int width)
{
if (NULL == src)
{
return;
}

if (width <= 0)
{
return;
}

printClockwiseRecursive(src, width, width - 1);
}
上面的是递归的实现方式, 我们可以很容的改成非递归的, 如下:

inline void printOne(const int val)
{
static int count = 0;
printf("%-4d", val);

if (++count == 10)
{
cout << endl;
count = 0;
}
}

void printClockwiseNonRecursive(const int *src, const int width, int cur)
{
while (cur > 0)
{
// print the up
for (register int i = 0; i < cur; ++i)
{
printOne(*src++);
}

// print the right
for (register int i = 0; i < cur; ++i)
{
printOne(*src);
src += width;
}

// print the bottom
for (register int i = cur; i > 0; --i)
{
printOne(*src--);
}

// for the left
for (register int i = cur; i > 0; --i)
{
printOne(*src);
src -= width;
}

src += width + 1;
cur -= 2;
}

if (0 == cur)
{
printOne(*src);
}
}

void printClockwise(const int *src, const int width)
{
if (NULL == src)
{
return;
}

if (width <= 0)
{
return;
}

printClockwiseNonRecursive(src, width, width - 1);
}


如果有错误欢迎指出, 分享请辨明

感觉好的话就顶一个, 感觉不错的话就踩一个。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息