How to resolve the algorithm Solve a Holy Knight's tour step by step in the Kotlin programming language

Published on 22 June 2024 08:30 PM

How to resolve the algorithm Solve a Holy Knight's tour step by step in the Kotlin programming language

Table of Contents

Problem Statement

Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following:

Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Solve a Holy Knight's tour step by step in the Kotlin programming language

Kotlin Code Overview:

This Kotlin code solves the Knight's Tour puzzle, which involves finding a sequence of moves for a knight on a chessboard such that it visits every square exactly once.

Code Structure:

1. Knight's Moves Array moves:

  • Defines the 8 possible knight's moves as 2D arrays of [-1, -2], [1, -2], etc., representing the relative coordinates from the current square.

2. Puzzle Boards board1 and board2:

  • Represent two puzzle boards with 'x' for open squares and 's' for the knight's starting position.

3. solve Function:

  • Recursive function that attempts to solve the Knight's Tour puzzle on a given board:
    • Takes parameters: pz (puzzle board), sz (board size), sx and sy (knight's starting position), idx (current move number), and cnt (total number of moves required).
    • Loops through possible knight's moves from the current position.
    • If a valid move is found, it updates the puzzle board and calls solve recursively for the next move.
    • If a solution is found (i.e., all squares are visited), it returns true. Otherwise, it returns false.

4. findSolution Function:

  • Parses the puzzle board string into a 2D array pz.
  • Locates the knight's starting position (x and y).
  • Initializes idx and cnt for tracking moves.
  • Calls solve to attempt a solution.
  • Prints the solution if found or an error message if not.

5. main Function:

  • Calls findSolution for two example puzzles (board1 and board2) and prints the solutions or error messages.

How the Code Works:

  1. The findSolution function reads a puzzle board string and converts it into a 2D array pz. It also identifies the knight's starting position.
  2. It initializes the idx (current move number) and cnt (total moves required) variables.
  3. The solve function is recursively called to attempt solving the puzzle.
  4. The solve function iterates through possible knight's moves from the current position.
  5. For each valid move, it updates the puzzle board and calls solve recursively for the next move.
  6. If a solution is found (i.e., all squares are visited), it returns true.
  7. If no solution is found, it backtracks and tries different moves.
  8. The findSolution function prints the solution if found or an error message if not.

Sample Outputs:

For board1:

02  03  06  09  12  14  08  13
01  --  05  10  11  15  07  14
04  --  --  --  --  --  --  --
10  --  --  --  --  --  --  --
09  --  --  --  --  --  --  --
16  18  21  24  26  27  20  22
17  19  23  24  28  29  20  22
20  24  25  29  28  --  21  23

For board2:

Cannot solve this puzzle!

Source code in the kotlin programming language

// version 1.1.3

val moves = arrayOf(
    intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1,  2), intArrayOf(1, 2),
    intArrayOf(-2, -1), intArrayOf(-2,  1), intArrayOf( 2, -1), intArrayOf(2, 1)
)

val board1 =
    " xxx    " +
    " x xx   " +
    " xxxxxxx" +
    "xxx  x x" +
    "x x  xxx" +
    "sxxxxxx " +
    "  xx x  " +
    "   xxx  "

val board2 =
    ".....s.x....." +
    ".....x.x....." +
    "....xxxxx...." +
    ".....xxx....." +
    "..x..x.x..x.." +
    "xxxxx...xxxxx" +
    "..xx.....xx.." +
    "xxxxx...xxxxx" +
    "..x..x.x..x.." +
    ".....xxx....." +
    "....xxxxx...." +
    ".....x.x....." +
    ".....x.x....."

fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean {
    if (idx > cnt) return true
    for (i in 0 until moves.size) {
        val x = sx + moves[i][0]
        val y = sy + moves[i][1]
        if ((x in 0 until sz) && (y in 0 until sz) && pz[x][y] == 0) {
            pz[x][y] = idx
            if (solve(pz, sz, x, y, idx + 1, cnt)) return true
            pz[x][y] = 0
        }
    }
    return false
}

fun findSolution(b: String, sz: Int) {
    val pz = Array(sz) { IntArray(sz) { -1 } }
    var x = 0
    var y = 0
    var idx = 0
    var cnt = 0
    for (j in 0 until sz) {
        for (i in 0 until sz) {
            if (b[idx] == 'x') {
                pz[i][j] = 0
                cnt++
            }
            else if (b[idx] == 's') {
                pz[i][j] = 1
                cnt++
                x = i
                y = j
            }
            idx++
        }
    }

    if (solve(pz, sz, x, y, 2, cnt)) {
        for (j in 0 until sz) {
            for (i in 0 until sz) {
                if (pz[i][j] != -1)
                    print("%02d  ".format(pz[i][j]))
                else
                    print("--  ")
            }
            println()
        }
    }
    else println("Cannot solve this puzzle!")
}

fun main(args: Array<String>) {
    findSolution(board1,  8) 
    println()
    findSolution(board2, 13)
}


  

You may also check:How to resolve the algorithm Percentage difference between images step by step in the E programming language
You may also check:How to resolve the algorithm Primality by Wilson's theorem step by step in the Ring programming language
You may also check:How to resolve the algorithm User input/Text step by step in the OCaml programming language
You may also check:How to resolve the algorithm Web scraping step by step in the Xidel programming language
You may also check:How to resolve the algorithm Sum of squares step by step in the Golfscript programming language