C# 创建 NxN 矩阵的方法

标签 c# algorithm matrix

我如何着手编写一个方法来创建一个填充的 nxn 矩阵,如下所示:

int[,] Matrix(int n) or int[][] Matrix(int n) for example for n = 5:

1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

最佳答案

一个解决方案是这样的:

static int[,] Matrix(int n)
{
    if (n < 0)
        throw new ArgumentException("n must be a positive integer.", "n");

    var result = new int[n, n];                    

    int level = 0,
        counter = 1;
    while (level < (int)Math.Ceiling(n / 2f))
    {
        // Start at top left of this level.
        int x = level, 
            y = level;
        // Move from left to right.
        for (; x < n - level; x++)           
            result[y, x] = counter++;            
        // Move from top to bottom.
        for (y++, x--; y < n - level; y++)            
            result[y, x] = counter++;            
        // Move from right to left.
        for (x--, y--; x >= level; x--)            
            result[y, x] = counter++;            
        // Move from bottom to top. Do not overwrite top left cell.
        for (y--, x++; y >= level + 1; y--)            
            result[y, x] = counter++;            
        // Go to inner level.
        level++;
    }

    return result;
}

这是输出到控制台的结果矩阵(n 在 1 到 6 之间):

Result

关于C# 创建 NxN 矩阵的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31152391/

相关文章:

c# - 通过网络在 C/C++ 服务器、C/C++ 和 C# 客户端之间发送数据结构

c# - TreatControlCAsInput 问题。这是一个错误吗?

algorithm - 难以理解解决Spoj DQuery的方法

python - Python 中的对角线网格遍历

c# - 如何编写加载 SQL Server 数据表的 Excel 插件?

c# - 为什么 var 是坏事?

algorithm - 查找具有多重因子的集合成员的所有产品

algorithm - 计算器(例如 Wolfram alpha)如何计算极大的阶乘?

java - 如何返回不同类中的转置矩阵?

python - 在稀疏矩阵上执行外积求和