gpt4 book ai didi

c# - 螺旋矩阵算法问题

转载 作者:行者123 更新时间:2023-11-29 06:17:45 24 4
gpt4 key购买 nike

大家好,我的代码正在填充螺旋矩阵。当 rows=columns 时它工作得很好但是当不同时它会在螺旋的第一个弯曲处给出错误!!!我试过用断点调试它,但没有发现任何错误!所以关于我的代码的一些额外提示:bentCounter 查找行或列何时被填充,如果是,它通过递增 j 来旋转螺旋线。当 j++ 使用数组 B 和 C 的下一个元素时,A 数组的索引 p、q 的方向就会改变!当我们同时填充行和列时,留下一个子矩阵,所以 n--;米--;当 j=3 时,它应该被取消以开始一个新的漩涡。希望已经足够清楚了!

static void Main(string[] args)
{
//n - quantity of rows, m - quantity of columns
// p,q - references to current element of The Matrix A[][]
// p=1, q=3 ----> A[0][3] - the element of crossing first row and fourth column

int p = 0;
int q = 0;
int j = 0;
int a = 0;
int b = 0;
int bentCounter = 0;

a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());

int n = a;
int m = b;
int mn = m * n;

int [,] A = new int [a,b];
int[] B = new int[] { 0, 1, 0, -1 };
int[] C = new int[] { 1, 0, -1, 0 };

for (int i = 0; i < mn ; i++)
{
bentCounter++;
if (bentCounter == n) {j++;}
if (bentCounter == m + n - 1)
{
if (j == 3) { j = -1; }
j++;
bentCounter = 0;
n--; m--;
}

A [p,q] = i;
p += B[j];
q += C[j];
}

for (int r = 0; r < A.GetLength(0); r++)
{
for (int c = 0; c < A.GetLength(1); c++)
{
Console.Write(" " + A[r, c] + " ");
}
Console.WriteLine();
}

10 倍感谢您的帮助BR

最佳答案

你以错误的方式增加维度并超出界限,一个快速的解决方案是将它们交换,所以将 int [,] A = new int [a,b] 更改为

int [,] A = new int [b,a];

一切都很好;)

编辑:同时更改此行以填充输出为您提供一个漂亮的方阵

Console.Write(" " + A[r, c].ToString().PadLeft(mn.ToString().Length, ' '));

关于c# - 螺旋矩阵算法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4431780/

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