螺旋算法的C#螺旋、算法

2023-09-11 22:41:52 作者:你不是怪胎

我如何填充数组像这样:

How can I fill an array like so:

1 2 3 4 5 6 7  8 
20 21 22 23 24 9
19 30 31 32 25 10
18 29 28 27 26 11
17 16 15 14 13 12

螺旋 C# 谢谢

Spiral C# Thanks

推荐答案

特拉弗斯从元素(0,0)开始的数组(左上),航向向右(增加你的列索引)。保持一个运行计数器递增每次填一个元素,以及对行,你必须列上限和下限尚未填补。用于M行×n列矩阵,你的行边界应该是0和(M-1),和色谱柱边界0和(N-1)。向右走,直到你打你的上一栏束缚,减小你的上栏的约束,往下走,直到你打你的上排约束,减小你的上排束缚,向左走,直到你打你的下栏的约束,增加你的下栏的约束,走起来直到你打你的下排的约束,增加您的下界,并重复,直到你的上,低的行或列边界相等(或直到你的跑步数为M * N)。

Traverse the array starting from element (0,0) (top-left), and heading right (incrementing your column index). Keep a running counter that increments each time you fill an element, as well as upper and lower bounds on the rows and columns you have yet to fill. For an M-row by N-column matrix, your row bounds should be 0 and (M-1), and your column bounds 0 and (N-1). Go right until you hit your upper column bound, decrement your upper column bound, go down until you hit your upper row bound, decrement your upper row bound, go left until you hit your lower column bound, increment your lower column bound, go up until you hit your lower row bound, increment your lower bound, and repeat until your upper and low row or column bounds are equal (or until your running count is M*N).