forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KnightsTour.cs
70 lines (67 loc) · 2.01 KB
/
KnightsTour.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
move Knight in a chess board such that it covers all the cells atleast once.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GFG
{
class Program
{
static void Main(String[] args)
{
int[,] board = new int[8,8];
Intialize(board);
int[] rowx = { 2, 1, -1, -2, -2, -1, 1, 2 };
int[] coly = { 1, 2, 2, 1, -1, -2, -2, -1 };
if (KnightsTour(board, 0, 0, 1,rowx,coly)) Display(board);
else Console.WriteLine("Solution does not exist");
}
private static void Intialize(int[,] board)
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
board[i, j]=-1;
}
}
board[0, 0] = 0;
}
private static void Display(int[,] board)
{
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
Console.Write(board[i,j]+" ");
}
Console.WriteLine();
}
}
private static bool KnightsTour(int[,] board, int row, int col,int move,int[] rowx,int[] coly)
{
if (move == 64) return true;
int nextx, nexty;
for(int k = 0; k < 8; k++)
{
nextx = row+rowx[k];
nexty = col+coly[k];
if (IsSafe(board, nextx, nexty))
{
board[nextx, nexty] = move;
if(KnightsTour(board,nextx,nexty,move+1,rowx,coly))return true;
board[nextx, nexty] = -1;
}
}
return false;
}
private static bool IsSafe(int[,] board, int row, int col)
{
if (row >= 0 && row < 8 && col >= 0 && col < 8 && board[row, col] == -1) return true;
return false;
}
}
}