c# - 螺旋矩阵算法问题

标签 c# java .net

大家好, 我的代码正在填充螺旋矩阵。 当 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/

相关文章:

c# - 从代码 ⇒ IL 或 IL ⇒ native 代码创建的引用在哪里

c# - 完全的 azure 新手 - 它是什么以及如何检查我的更改是否已提交

c# - 为什么 NotifyCollectionChangedEventArgs.NewItems 属性是一个列表?

c# - 更换表格的最佳方法?

c# - 在 xUnit.net 中的所有测试之前和之后运行一次代码

java - 可以使用此模式进行值检查吗?

java - 如何重构创建 Intent 的重复代码?

java - 如何将一种语言(例如 python)绑定(bind)到另一种语言(例如 C++)?

c# - 表中列值的总和 - Rdlc 报告

c# - .NET/C# 上有一种 isset() 吗?