C#语言递归实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static int[,] a = new int[100, 100];
static int cnt = 0, s;
static bool judge(int n, int i)
{
int k, j;
for (j = 0; j < n; j++)
{
if (a[j, i] == 1) return false;
}
for (j = n - 1, k = i - 1; j >= 0 && k >= 0; j--, k--)//向右下方检查
{
if (a[j, k] == 1) return false;
}
for (j = n - 1, k = i + 1; j >= 0 && k < s; j--, k++)//向右上方检查
{
if (a[j, k] == 1) return false;
}
return true;
}
static void f(int n)
{
if (n == s) { cnt++; return; }
for (int i = 0; i < s; i++)
{
if (judge(n, i))
{
a[n, i] = 1;
f(n + 1);
a[n, i] = 0;
}
}
}
static void Main(string[] args)
{
s = int.Parse(Console.ReadLine());
f(0);
Console.WriteLine(cnt);
}
}
}