using
System;
using
System.Collections;
using
System.Collections.Generic;
public
class
GFG{
public
static
int
N = 8;
public
int
[] cx =
new
int
[] {1, 1, 2, 2, -1, -1, -2, -2};
public
int
[] cy =
new
int
[] {2, -2, 1, -1, 2, -2, 1, -1};
bool
limits(
int
x,
int
y)
{
return
((x >= 0 && y >= 0) && (x < N && y < N));
}
bool
isempty(
int
[] a,
int
x,
int
y)
{
return
((limits(x, y)) && (a[y * N + x] < 0));
}
int
getDegree(
int
[] a,
int
x,
int
y)
{
int
count = 0;
for
(
int
i = 0; i < N; ++i)
if
(isempty(a, (x + cx[i]),
(y + cy[i])))
count++;
return
count;
}
Cell nextMove(
int
[] a, Cell cell)
{
int
min_deg_idx = -1, c,
min_deg = (N + 1), nx, ny;
Random random =
new
Random();
int
start=random.Next(0, 1000);
for
(
int
count = 0; count < N; ++count)
{
int
i = (start + count) % N;
nx = cell.x + cx[i];
ny = cell.y + cy[i];
if
((isempty(a, nx, ny)) &&
(c = getDegree(a, nx, ny)) < min_deg)
{
min_deg_idx = i;
min_deg = c;
}
}
if
(min_deg_idx == -1)
return
null
;
nx = cell.x + cx[min_deg_idx];
ny = cell.y + cy[min_deg_idx];
a[ny * N + nx] = a[(cell.y) * N +
(cell.x)] + 1;
cell.x = nx;
cell.y = ny;
return
cell;
}
void
print(
int
[] a)
{
for
(
int
i = 0; i < N; ++i)
{
for
(
int
j = 0; j < N; ++j)
Console.Write(a[j * N + i]+
"\t"
);
Console.Write(
"\n"
);
}
}
bool
neighbour(
int
x,
int
y,
int
xx,
int
yy)
{
for
(
int
i = 0; i < N; ++i)
if
(((x + cx[i]) == xx) &&
((y + cy[i]) == yy))
return
true
;
return
false
;
}
bool
findClosedTour()
{
int
[] a =
new
int
[N * N];
for
(
int
i = 0; i < N * N; ++i)
a[i] = -1;
int
sx = 3;
int
sy = 2;
Cell cell =
new
Cell(sx, sy);
a[cell.y * N + cell.x] = 1;
Cell ret =
null
;
for
(
int
i = 0; i < N * N - 1; ++i)
{
ret = nextMove(a, cell);
if
(ret ==
null
)
return
false
;
}
if
(!neighbour(ret.x, ret.y, sx, sy))
return
false
;
print(a);
return
true
;
}
static
public
void
Main (){
while
(!
new
GFG().findClosedTour())
{
;
}
}
}
class
Cell
{
public
int
x;
public
int
y;
public
Cell(
int
x,
int
y)
{
this
.x = x;
this
.y = y;
}
}