可能的算法打印螺旋矩阵 [英] possible algorithms for printing spiral matrix

查看:158
本文介绍了可能的算法打印螺旋矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有打印:(对于n = 4)

let's say we have to print:(for n=4)

 1  2  3 4
12 13 14 5
11 16 15 6
10  9  8 7

这仅仅是对于n​​ = 4的示例输出,算法应该是GENRAL对所有整体数字 我认为,试图code思考指标的螺旋状旋转怎么回事,即

this is just an sample output for n=4, algorithm should be genral for all integral numbers I thought and tried to code thinking for the spiral rotation of indexes going on here ,i.e

element: 1 - 2 - 3 - 4 - 5...->16
indexes: 00-01-02-03-13-23...-21

但指数这种螺旋状旋转并没有给我足够的图案将成为一个完整的算法。

but this spiral rotation of index doesn't give me enough pattern for putting into a complete algorithm.

然后我采取了完全不同的方法,通过检查指标没有。行和列按顺序打印的:

then I took a totally different approach by checking the index no. of row and column printed in sequence:

    row       coloumn
1>  0    ->       n-1
2> n-1  ->         0
3>   1    ->      n-2
4> n-2  ->         1

但我仍然停留在书面的算法this.I不希望我的小伙子们写codeS的答案,所以请你只

but I am still stuck in writing algorithm for this.I don't want my fellas to write codes in answer so please just

纠正我在我的上面,或者如果您有任何新的算法,这样做的话,请提供了新的方法来解决这个问题。提到的算法?

推荐答案

我有很多的乐趣看着我,否则称职的教师想出了迭代矩阵为螺旋显然,聪明的和短的方式,但没有他们的工作权当我实现了他们。

I've had a lot of fun watching my otherwise competent teachers come up with apparently-smart and short ways of iterating a matrix as a spiral, but none of them worked right when I implemented them.

所以,我的建议是,你不要去想任何方式或编码快捷方式来完成这件事。您将几乎肯定弄错了,花了很多的时间调试。相反,只是模拟简单的条件和更新的动作:

So what I suggest is you don't think about any pattern or coding shortcut to get this done. You will almost certainly get it wrong and spend a lot of time debugging. Instead, just simulate the moves with simple conditions and updates:

1. Move right until you hit the right bonundary, then move one step down if possible
   and increment the top boundary;
2. Move down until you hit the bottom boundary, then move one step left if possible
   and decrement the right boundary;
3. Move left until you hit the left boundary, then move one step up if possible
   and decrement the bottom boundary;
4. Move up until you hit the top boundary, then move one step right if possible
   and increment the left boundary. Go to step (1).

这将导致更多的code,但是这将是更具可读性和更少的错误倾向。

It will lead to a bit more code, but it will be much more readable and much less bug prone.

这篇关于可能的算法打印螺旋矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆