问题描述
- link如何解决如下矩阵生成难题?注意一定要用link实现。
-
将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;
}
}
}
时间: 2024-12-03 00:53:51