问题描述
- link如何解决如下矩阵生成难题
-
将1~N*N放入一个N*N的矩阵,要求矩阵每行每列以及对角线的和相等。请问怎么实现?
解决方案
解决方案二:
这是算法题, 和LINQ没有关系
解决方案三:
using System;
using System.Collections.Generic;
using System.Text;
namespace MagicMatrix
{
class Program
{
int[,] mm;
static void Main(string[] args)
{
do
{
Program p1 = new Program();
int n;
Console.WriteLine("请输入矩阵的大小:");
n = int.Parse(Console.ReadLine());
if (n == 0)
{
Console.WriteLine("请按Enter键离开!");
break;
}
if (n % 2 == 0)
{
Console.WriteLine("请输入奇数!");
break;
}
p1.mm = new int[n, n];
p1.AssingValue(n);
p1.PrintOut(n);
Console.WriteLine("n");
} while (true);
Console.ReadLine();
}
void AssingValue(int n)
{
int assingValue = 1;
int p = n - 1;
int column = p / 2;
int row = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
mm[i, j] = 0;
}
}
mm[row, column] = assingValue;
do
{
assingValue++;
column--;
row--;
if (column < 0 && row < 0)
{
column++;
row++;
row++;
}
else
{
if (column < 0)
{
column = p;
}
if (row < 0)
{
row = p;
}
if (mm[row, column] != 0)
{
row += 2;
column += 1;
}
if (row > n - 1)
{
row = 0;
}
if (column > n - 1)
{
column = 0;
}
}
mm[row, column] = assingValue;
} while (assingValue < n * n);
}
void PrintOut(int n)
{
for (int i = 0; i < n; i++)
{
Console.WriteLine();
for (int j = 0; j < n; j++)
{
Console.Write(mm[i, j] + "t");
}
}
}
}
}
时间: 2024-09-30 18:39:07