我想问是否有一些算法准备好,允许我这样做:我有一个矩阵 m(列)x n(行),其中有 m x n 元素。我想给这个元素从中心开始并以螺旋形式旋转的位置,例如,对于 3x3 的矩阵,我有 9 个这样定义的元素:
5 6 7
4 9 8
3 2 1
或者对于 una 矩阵 4 x 3 我有 12 个元素,请定义:
8 9 10 1
7 12 11 2
6 5 4 3
或者,一个 5x2 的矩阵有 10 个元素,如下定义:
3 4
7 8
10 9
6 5
2 1
ETC。
我已经基本上解决了定义 m x n 元素的整数数组并手动加载值的问题,但对我来说,就像自动由算法生成的矩阵一样。
感谢谁能帮我找到一些东西,非常感谢。
UPDATE
这段代码,完全符合我想要的,但不是在delphi中;只是我需要从 1 开始,而不是从 0 开始。对我来说重要的是它对任何矩阵 m x n 都有效。谁帮我翻译一下delphi?
(defun spiral (rows columns)
(do ((N (* rows columns))
(spiral (make-array (list rows columns) :initial-element nil))
(dx 1) (dy 0) (x 0) (y 0)
(i 0 (1+ i)))
((= i N) spiral)
(setf (aref spiral y x) i)
(let ((nx (+ x dx)) (ny (+ y dy)))
(cond
((and (< -1 nx columns)
(< -1 ny rows)
(null (aref spiral ny nx)))
(setf x nx
y ny))
(t (psetf dx (- dy)
dy dx)
(setf x (+ x dx)
y (+ y dy)))))))
> (pprint (spiral 6 6))
#2A ((0 1 2 3 4 5)
(19 20 21 22 23 6)
(18 31 32 33 24 7)
(17 30 35 34 25 8)
(16 29 28 27 26 9)
(15 14 13 12 11 10))
> (pprint (spiral 5 3))
#2A ((0 1 2)
(11 12 3)
(10 13 4)
(9 14 5)
(8 7 6))
再次非常感谢。
基于经典螺旋算法 http://rosettacode.org/wiki/Spiral_matrix。支持非方阵:
program SpiralMatrix;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TMatrix = array of array of Integer;
procedure PrintMatrix(const a: TMatrix);
var
i, j: Integer;
begin
for i := 0 to Length(a) - 1 do
begin
for j := 0 to Length(a[0]) - 1 do
Write(Format('%3d', [a[i, j]]));
Writeln;
end;
end;
var
spiral: TMatrix;
i, m, n: Integer;
row, col, dx, dy,
dirChanges, visits, temp: Integer;
begin
m := 3; // columns
n := 3; // rows
SetLength(spiral, n, m);
row := 0;
col := 0;
dx := 1;
dy := 0;
dirChanges := 0;
visits := m;
for i := 0 to n * m - 1 do
begin
spiral[row, col] := i + 1;
Dec(visits);
if visits = 0 then
begin
visits := m * (dirChanges mod 2) + n * ((dirChanges + 1) mod 2) - (dirChanges div 2) - 1;
temp := dx;
dx := -dy;
dy := temp;
Inc(dirChanges);
end;
Inc(col, dx);
Inc(row, dy);
end;
PrintMatrix(spiral);
Readln;
end.
3 x 3:
1 2 3
8 9 4
7 6 5
4 x 3:
1 2 3 4
10 11 12 5
9 8 7 6
2 x 5:
1 2
10 3
9 4
8 5
7 6
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)