將1~N*N放入一個N*N的矩陣,要求矩陣每行每列以及對角線的和相等。請問怎麼實現?注意一定要用link實現。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int n = 3;
var result = solve(n, new int[] { }).First();
for (int i = 0; i < n; i++)
{
Console.WriteLine(string.Join("\t", result.Skip(i * n).Take(n).Select(x => x.ToString())));
}
}
static IEnumerable<int[]> solve(int n, int[] current)
{
if (current.Length == n * n)
{
yield return current;
yield break;
}
foreach (int item in Enumerable.Range(1, n * n).Where(x => !current.Contains(x) && foo(n, current, x)))
{
foreach (var i in solve(n, current.Concat(new int[] { item }).ToArray()))
yield return i;
}
}
static bool foo(int n, int[] current, int next)
{
int[] arr = current.Concat(new int[] { next }).Concat(Enumerable.Repeat(0, n * n - current.Length - 1)).ToArray();
int sum3 = 0, sum4 = 0;
for (int i = 0; i < n; i++)
{
int sum1 = 0, sum2 = 0;
for (int j = 0; j < n; j++)
{
sum1 += arr[i * n + j];
sum2 += arr[j * n + i];
}
if (new int[] { sum1, sum2 }.Any(x => x > n * n / 2 + 1)) return false;
sum3 += arr[i * n + i];
sum4 += arr[i * n + (n - i)];
}
if (new int[] { sum3, sum4 }.Any(x => x > n * n / 2 + 1)) return false;
return true;
}
}
}