gpt4 book ai didi

algorithm - 矩阵和算法 "spiral"

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:34:22 26 4
gpt4 key购买 nike

我想问一下是否有一些算法可以让我这样做:我有一个矩阵 m (col) x n (row),其中有 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

等我基本上已经解决了定义一个 m x n 元素的整数数组并手动加载值的问题,但对我来说一般来说就像自动由算法生成的矩阵一样。感谢谁能帮我找到这样的东西,非常感谢。

更新

这段代码,完全符合我的要求,但不是在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))

再次感谢。

最佳答案

基于经典spiral algorithm .支持非方阵:

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

关于algorithm - 矩阵和算法 "spiral",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8757514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com