Побывать конем на всех клетках шахматной доски - C#
Формулировка задачи:
Задача побывать конем на всех клетках шахматной доски. На каждой клетке можно побывать только 1 раз. Делал через рекурсия. Работает до 45, затем наступает переполнение стека вызовов. Почему?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace chess3
{
class Program
{
struct ind
{
public Byte i, j;
}
static Byte n1 = 8, n2 = 8;
static void Main(string[] args)
{
Byte[,] matr=new Byte[n1,n2];
for(Byte i=0;i<n1;i++)
for(Byte j=0;j<n2;j++)
{
matr[i,j]=0;
}
matr[0,0]=1;
Byte count=1;
shag(matr, count);
Console.ReadLine();
}
static void shag(Byte[,] matr,Byte count)
{
bool flag = false;
Byte x=0,y=0;
for(Byte i=0;i<n1;i++)
{
for (Byte j = 0; j < n1; j++)
{
if(matr[i,j]==count)
{
x = i; y = j;
}
}
}
ind[] Ind = new ind[n1];
for (Byte i = 0; i < n1;i++)
{
Ind[i].i = x;
Ind[i].j = y;
}
Ind[0].i += 2; Ind[0].j++;
Ind[1].i += 2; Ind[1].j--;
Ind[2].i -= 2; Ind[2].j++;
Ind[3].i -= 2; Ind[3].j--;
Ind[4].i++; Ind[4].j += 2;
Ind[5].i++; Ind[5].j -= 2;
Ind[6].i--; Ind[6].j += 2;
Ind[7].i--; Ind[7].j -= 2;
if (count ==64)
{
Console.WriteLine("count= " + count);
for (Byte i = 0; i < n1; i++)
{
for (Byte j = 0; j < n2; j++)
{
if (matr[i, j] < 10)
Console.Write(matr[i, j] + " ");
else
Console.Write(matr[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
else if(count>63)
{
}
else if(count<0)
{
Console.WriteLine("Error");
}
else
{
for (Byte i1 = 0; i1 < 8; i1++)
{
if (Ind[i1].i >= 0 && Ind[i1].i < 8 && Ind[i1].j >= 0 && Ind[i1].j < 8 && matr[Ind[i1].i, Ind[i1].j] == 0)
{
matr[Ind[i1].i, Ind[i1].j] = (Byte)(count+1);
for (Byte i = 0; i < n1; i++)
{
for (Byte j = 0; j < n2; j++)
{
if(matr[i,j]==(count+1) && i!=Ind[i1].i && j!=Ind[i1].j)
{
matr[i, j] = 0;
}
}
}
shag(matr,(Byte)(count+1));
flag = true;
break;
}
}
if(flag==false && count>0)
{
shag(matr, (Byte)(count - 1));
}
}
}
}
}Решение задачи: «Побывать конем на всех клетках шахматной доски»
textual
Листинг программы
ind[] Ind = new ind[n1];