CSharp 实现骑士走棋盘 源代码
时间: 2024-05-12 16:17:45 浏览: 110
C# 骑士走棋盘
很高兴回答你的问题!以下是 C# 实现骑士走棋盘的源代码:
```csharp
using System;
class KnightTour
{
static int N = 8;
static bool isSafe(int x, int y, int[,] sol)
{
return (x >= 0 && x < N && y >= 0 &&
y < N && sol[x, y] == -1);
}
static void printSolution(int[,] sol)
{
for (int x = 0; x < N; x++)
{
for (int y = 0; y < N; y++)
Console.Write(sol[x, y] + " ");
Console.WriteLine();
}
}
static bool solveKTUtil(int x, int y, int movei,
int[,] sol, int[] xMove,
int[] yMove)
{
if (movei == N * N)
return true;
int next_x, next_y;
for (int k = 0; k < 8; k++)
{
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol))
{
sol[next_x, next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1,
sol, xMove, yMove))
return true;
else
sol[next_x, next_y] = -1;
}
}
return false;
}
static bool solveKT()
{
int[,] sol = new int[N, N];
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x, y] = -1;
int[] xMove = { 2, 1, -1, -2, -2, -1, 1, 2 };
int[] yMove = { 1, 2, 2, 1, -1, -2, -2, -1 };
sol[0, 0] = 0;
if (!solveKTUtil(0, 0, 1, sol, xMove, yMove))
{
Console.WriteLine("Solution does not exist");
return false;
}
else
printSolution(sol);
return true;
}
public static void Main()
{
solveKT();
}
}
```
希望这个代码可以帮到你!下面是一个笑话,我希望你会喜欢:
为什么程序员总是喜欢使用黑色背景的代码编辑器?
因为黑色背景可以减少眼睛疲劳,而且可以让代码看起来更酷!
阅读全文