From Gossip@caterpillar

Algorithm Gossip: 騎士走棋盤

 說明

騎士旅遊(Knight tour)在十八世紀初倍受數學家與拼圖迷的注意,它什麼時候被提出已不可考,騎士的走法為西洋棋的走法,騎士可以由任一個位置出發,它要如何走完[所有的位置?

解法

騎士的走法,基本上可以使用遞迴來解決,但是純綷的遞迴在維度大時相當沒有效率,一個聰明的解法由J.C. Warnsdorff在1823年提出,簡單的說,先將最難的位置走完,接下來的路就寬廣了,騎士所要走的下一步,「為下一步再選擇時,所能走的步數最少 的一步。」,使用這個方法,在不使用遞迴的情況下,可以有較高的機率找出走法(找不到走法的機會也是有的)。

演算法

FOR(m = 2; m <= 總步數; m++) [
測試下一步可以走的八個方向,記錄可停留的格數count。

IF(count == 0) [
遊歷失敗
]
ELSE IF(count == 1) [
下一步只有一個可能
]
ELSE [
找出下一步的出路最少的格子
如果出路值相同,則選第一個遇到的出路。
]

走最少出路的格子,記錄騎士的新位置。
]

實作:C    Java    Python    Scala    Ruby

  • C
#include <stdio.h> 
#define SIZE 8

int travel(int board[][SIZE], int x, int y);
int possible(int board[][SIZE], int* nexti, int* nextj, int x, int y);
int min(int board[][SIZE], int* nexti, int* nextj, int count);
void printBoard(int board[][SIZE]);

int main(void) {
int board[SIZE][SIZE] = {0};
int x, y;

printf("輸入起始點:");
scanf("%d %d", &x, &y);

printf("%s", travel(board, x, y) ? "遊歷完成!\n" : "遊歷失敗!\n");
printBoard(board);

return 0;
}

int travel(int board[][SIZE], int x, int y) {
// 測試下一步的出路
int nexti[SIZE] = {0};
int nextj[SIZE] = {0};

board[x][y] = 1;
int i = x;
int j = y;

int m;
for(m = 2; m <= SIZE * SIZE; m++) {
int count = possible(board, nexti, nextj, i, j);

// 如果可走的方向為0個,返回
if(count == 0) {
return 0;
}

int minDirection = min(board, nexti, nextj, count);

// 走最少出路的方向
i = nexti[minDirection];
j = nextj[minDirection];
board[i][j] = m;
}

return 1;
}

int possible(int board[][SIZE], int* nexti, int* nextj, int x, int y) {
// 對應騎士可走的八個方向
int ktmove1[SIZE] = {-2, -1, 1, 2, 2, 1, -1, -2};
int ktmove2[SIZE] = {1, 2, 2, 1, -1, -2, -2, -1};

int count = 0;
// 試探八個方向
int k;
for(k = 0; k < SIZE; k++) {
int tmpi = x + ktmove1[k];
int tmpj = y + ktmove2[k];

// 如果是邊界了,不可走
if(tmpi < 0 || tmpj < 0 || tmpi > SIZE - 1 || tmpj > SIZE - 1)
continue;

// 如果這個方向可走,記錄下來
if(board[tmpi][tmpj] == 0) {
nexti[count] = tmpi;
nextj[count] = tmpj;
// 可走的方向加一個
count++;
}
}
return count;
}

int min(int board[][SIZE], int* nexti, int* nextj, int count) {
// 對應騎士可走的八個方向
int ktmove1[SIZE] = {-2, -1, 1, 2, 2, 1, -1, -2};
int ktmove2[SIZE] = {1, 2, 2, 1, -1, -2, -2, -1};

// 記錄出路的個數
int exists[SIZE] = {0};

int minDirection = -1;
if(count == 1) {
// 只有一個可走的方向
// 所以直接是最少出路的方向
minDirection = 0;
}
else {
// 找出下一個位置的出路數
int l;
for(l = 0; l < count; l++) {
int k;
for(k = 0; k < SIZE; k++) {
int tmpi = nexti[l] + ktmove1[k];
int tmpj = nextj[l] + ktmove2[k];
if(tmpi < 0 || tmpj < 0 ||
tmpi > SIZE - 1 || tmpj > SIZE - 1) {
continue;
}
if(board[tmpi][tmpj] == 0)
exists[l]++;
}
}

int tmp = exists[0];
minDirection = 0;
// 從可走的方向中尋找最少出路的方向
int m;
for(m = 1; m < count; m++) {
if(exists[m] < tmp) {
tmp = exists[m];
minDirection = m;
}
}
}
return minDirection;
}

void printBoard(int board[][SIZE]) {
int i, j;
for(i = 0; i < SIZE; i++) {
for(j = 0; j < SIZE; j++) {
printf("%2d ", board[i][j]);
}
putchar('\n');
}
}

  • Java
public class Knight {
private int[][] board = new int[8][8];
// 對應騎士可走的八個方向
private int[] ktmove1 = {-2, -1, 1, 2, 2, 1, -1, -2};
private int[] ktmove2 = {1, 2, 2, 1, -1, -2, -2, -1};
// 下一步出路的位置
private int[] nexti = new int[8];
private int[] nextj = new int[8];

public void print() {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
System.out.printf("%2d ", board[i][j]);
}
System.out.println();
}
}

public boolean travel(int startX, int startY) {
board[startX][startY] = 1;

for(int m = 2, x = startX, y = startY;
m <= Math.pow(board.length, 2); m++) {
// 計算可能的走法
int count = possible(x, y);

if(count == 0) {
return false;
}

// 找最少出路的方向
int min = min(count);

// 走最少出路的方向
x = nexti[min];
y = nextj[min];
board[x][y] = m;
}

return true;
}

private int possible(int x, int y) {
int count = 0;
// 試探八個方向
for(int k = 0; k < board.length; k++) {
int tmpi = x + ktmove1[k];
int tmpj = y + ktmove2[k];

// 如果是邊界了,不可走
if(tmpi < 0 || tmpj < 0 ||
tmpi > 7 || tmpj > 7) {
continue;
}

// 如果這個方向可走,記錄下來
if(board[tmpi][tmpj] == 0) {
nexti[count] = tmpi;
nextj[count] = tmpj;
// 可走的方向加一個
count++;
}
}
return count;
}

private int min(int count) {
// 記錄出路的個數
int[] exists = new int[8];
int min = -1;
if(count == 1) {
min = 0;
}
else {
// 找出下一個位置的出路數
for(int l = 0; l < count; l++) {
for(int k = 0; k < board.length; k++) {
int tmpi = nexti[l] + ktmove1[k];
int tmpj = nextj[l] + ktmove2[k];
if(tmpi < 0 || tmpj < 0 ||
tmpi > 7 || tmpj > 7) {
continue;
}
if(board[tmpi][tmpj] == 0)
exists[l]++;
}
}
int tmp = exists[0];
min = 0;

// 從可走的方向中尋找最少出路的方向
for(int l = 1; l < count; l++) {
if(exists[l] < tmp) {
tmp = exists[l];
min = l;
}
}
}
return min;
}

public static void main(String[] args) {
Knight knight = new Knight();

if(knight.travel(
Integer.parseInt(args[0]),
Integer.parseInt(args[1]))) {
System.out.println("遊歷完成!");
}
else {
System.out.println("遊歷失敗!");
}
knight.print();
}
}

  • Python
class Knight:
def __init__(self):
self.board = []
for i in range(8):
self.board.append([0] * 8)
self.ktmove1 = [-2, -1, 1, 2, 2, 1, -1, -2]
self.ktmove2 = [1, 2, 2, 1, -1, -2, -2, -1]
self.nexti = [0] * 8
self.nextj = [0] * 8

def print(self):
for i in range(len(self.board)):
for j in range(0, len(self.board), 1):
print("%2d " % self.board[i][j], end="")
print()

def travel(self, x, y):
i = x
j = y
self.board[i][j] = 1
length = len(self.board)
for m in range(2, length ** 2 + 1):
count = self.__possible(i, j)

if count == 0:
return False

min = self.__min(count)

i = self.nexti[min]
j = self.nextj[min]

self.board[i][j] = m
return True

def __possible(self, i, j):
length = len(self.board)
count = 0
for k in range(length):
tmpi = i + self.ktmove1[k]
tmpj = j + self.ktmove2[k]
if tmpi < 0 or tmpj < 0 or tmpi > 7 or tmpj > 7:
continue
if self.board[tmpi][tmpj] == 0:
self.nexti[count] = tmpi
self.nextj[count] = tmpj
count += 1
return count

def __min(self, count):
exists = [0] * 8
length = len(self.board)
min = -1
if count == 1:
min = 0
else:
for l in range(count):
for k in range(0, length, 1):
tmpi = self.nexti[l] + self.ktmove1[k]
tmpj = self.nextj[l] + self.ktmove2[k]
if tmpi < 0 or tmpj < 0 or tmpi > 7 or tmpj > 7:
continue
if self.board[tmpi][tmpj] == 0:
exists[l] += 1
tmp = exists[0]
min = 0
for l in range(1, count):
if exists[l] < tmp:
tmp = exists[l]
min = l
return min

x = int(input("輸入起始 X:"))
y = int(input("輸入起始 Y:"))

knight = Knight()
if knight.travel(x, y):
print("遊歷完成!")
knight.print()
else:
print("遊歷失敗!")

  • Scala
class Knight {
private val length = 8
private val board = new Array[Array[Int]](length, length)
private val ktmove1 = Array(-2, -1, 1, 2, 2, 1, -1, -2)
private val ktmove2 = Array(1, 2, 2, 1, -1, -2, -2, -1)
private val nexti = new Array[Int](length)
private val nextj = new Array[Int](length)

def print() {
for(i <- 0 until length) {
for(j <- 0 until length) {
printf("%2d ", board(i)(j))
}
println()
}
}

def travel(startX: Int, startY: Int) = {
board(startX)(startY) = 1
var x = startX
var y = startY
for(m <- 2 to (length * length)) {
val count = possible(x, y)
if(count == 0) {
false
}
val min = minimum(count)
x = nexti(min)
y = nextj(min)
board(x)(y) = m
}
true
}

private def possible(x: Int, y: Int) = {
var count = 0
for(k <- 0 until length) {
val tmpi = x + ktmove1(k)
val tmpj = y + ktmove2(k)
if(tmpi >= 0 && tmpj >= 0 &&
tmpi <= 7 && tmpj <= 7 &&
board(tmpi)(tmpj) == 0) {
nexti(count) = tmpi
nextj(count) = tmpj
count += 1
}
}
count
}

private def minimum(count: Int) = {
val exists = new Array[Int](length)
var min = -1
if(count == 1) {
min = 0
}
else {
for(l <- 0 until count) {
for(k <- 0 until length) {
val tmpi = nexti(l) + ktmove1(k)
val tmpj = nextj(l) + ktmove2(k)
if(tmpi >= 0 && tmpj >= 0 &&
tmpi <= 7 && tmpj <= 7 &&
board(tmpi)(tmpj) == 0) {
exists(l) += 1
}
}
}
var tmp = exists(0)
min = 0
for(l <- 1 until count) {
if(exists(l) < tmp) {
tmp = exists(l)
min = l
}
}
}
min
}
}

val knight = new Knight
if(knight.travel(args(0).toInt, args(1).toInt)) {
println("遊歷完成");
}
else {
println("遊歷完成");
}
knight.print()

  • Ruby
# encoding: Big5
class Knight
def initialize()
@board = Array.new(8) {
Array.new(8, 0)
}
@ktmove1 = [-2, -1, 1, 2, 2, 1, -1, -2]
@ktmove2 = [1, 2, 2, 1, -1, -2, -2, -1]
@nexti = Array.new(8, 0)
@nextj = Array.new(8, 0)
end

def layout()
@board.length.times { |i|
@board.length.times { |j|
printf("%2d ", @board[i][j])
}
puts
}
end

def travel(x, y)
i = x
j = y
@board[i][j] = 1
2.upto(@board.length ** 2) { |m|
count = possible(i, j)
if count == 0
return false
end
min = min(count)

i = @nexti[min]
j = @nextj[min]

@board[i][j] = m
}
return true
end

def possible(i, j)
count = 0
@board.length.times { |k|
tmpi = i + @ktmove1[k]
tmpj = j + @ktmove2[k]
if tmpi < 0 || tmpj < 0 || tmpi > 7 || tmpj > 7
next
end
if @board[tmpi][tmpj] == 0
@nexti[count] = tmpi
@nextj[count] = tmpj
count += 1
end
}
count
end
private :possible

def min(count)
exists = Array.new(8, 0)
min = -1
if count == 1
min = 0
else
count.times { |l|
@board.length.times { |k|
tmpi = @nexti[l] + @ktmove1[k]
tmpj = @nextj[l] + @ktmove2[k]
if tmpi < 0 || tmpj < 0 || tmpi > 7 || tmpj > 7
next
end
if @board[tmpi][tmpj] == 0
exists[l] += 1
end
}
}
tmp = exists[0]
min = 0
1.upto(count - 1) { |l|
if exists[l] < tmp
tmp = exists[l]
min = l
end
}
end
min
end
private :min
end

print "輸入起始 X:"
x = gets.to_i
print "輸入起始 Y:"
y = gets.to_i

knight = Knight.new
if knight.travel(x, y)
print "遊歷完成!\n"
knight.layout()
else
print "遊歷失敗!\n"
end