How to resolve the algorithm Solve a Hidato puzzle step by step in the Go programming language

Published on 12 May 2024 09:40 PM
#Go

How to resolve the algorithm Solve a Hidato puzzle step by step in the Go programming language

Table of Contents

Problem Statement

The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: For example the following problem has the following solution, with path marked on it:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Solve a Hidato puzzle step by step in the Go programming language

The provided code is a Go program that solves a sliding puzzle. The objective of the puzzle is to move the numbered tiles in a grid to their correct positions, typically starting from a scrambled state. The code uses a backtracking algorithm to find a solution to the puzzle.

Here's a detailed explanation of the code:

  1. Input: The input to the program is a slice of strings, where each string represents a row of the puzzle board. The presence of an underscore ('_') indicates an empty cell, while numerical values represent tiles that need to be moved. The sample input provided in the code represents a 9x9 puzzle board with some pre-filled values.

  2. Setup: The setup function initializes the data structures used to represent the puzzle. It creates a two-dimensional slice board to store the state of the puzzle board, where each element represents a cell. Initially, all cells are set to -1, except for the pre-filled tiles which are set to their respective values.

    The start variable stores the coordinates of the starting cell (the cell containing the number 1). The given variable stores the list of all the numbers that need to be arranged on the board, sorted in ascending order.

  3. Solution Algorithm: The solve function is a recursive backtracking function that attempts to find a solution to the puzzle. It takes four parameters:

    • r and c: the row and column of the current cell being considered.
    • n: the value to be placed in the current cell.
    • next: the index of the next value in the given list that should be placed on the board.

    The algorithm works by trying all possible moves from the current cell and recursively exploring the resulting states. For each move, it checks if moving there is valid, i.e., the next value in the given list matches the target cell, and if not, it backtracks to try a different move.

    The algorithm keeps track of the state of the board as it explores different moves, and if a valid sequence of moves is found that results in the puzzle being solved, it returns true.

  4. Printing the Solution: After the puzzle is solved, the printBoard function prints the final state of the board to the console. The function prints the board with the correct values placed in the cells and empty cells represented as "__".

  5. Main Function: The main function sets up the puzzle and then calls the solve function to find a solution. If a solution is found, it prints the solved board.

Source code in the go programming language

package main

import (
    "fmt"
    "sort"
    "strconv"
    "strings"
)

var board [][]int
var start, given []int

func setup(input []string) {
    /* This task is not about input validation, so
       we're going to trust the input to be valid */
    puzzle := make([][]string, len(input))
    for i := 0; i < len(input); i++ {
        puzzle[i] = strings.Fields(input[i])
    }
    nCols := len(puzzle[0])
    nRows := len(puzzle)
    list := make([]int, nRows*nCols)
    board = make([][]int, nRows+2)
    for i := 0; i < nRows+2; i++ {
        board[i] = make([]int, nCols+2)
        for j := 0; j < nCols+2; j++ {
            board[i][j] = -1
        }
    }
    for r := 0; r < nRows; r++ {
        row := puzzle[r]
        for c := 0; c < nCols; c++ {
            switch cell := row[c]; cell {
            case "_":
                board[r+1][c+1] = 0
            case ".":
                break
            default:
                val, _ := strconv.Atoi(cell)
                board[r+1][c+1] = val
                list = append(list, val)
                if val == 1 {
                    start = append(start, r+1, c+1)
                }
            }
        }
    }
    sort.Ints(list)
    given = make([]int, len(list))
    for i := 0; i < len(given); i++ {
        given[i] = list[i]
    }
}

func solve(r, c, n, next int) bool {
    if n > given[len(given)-1] {
        return true
    }

    back := board[r][c]
    if back != 0 && back != n {
        return false
    }

    if back == 0 && given[next] == n {
        return false
    }

    if back == n {
        next++
    }

    board[r][c] = n
    for i := -1; i < 2; i++ {
        for j := -1; j < 2; j++ {
            if solve(r+i, c+j, n+1, next) {
                return true
            }
        }
    }

    board[r][c] = back
    return false
}

func printBoard() {
    for _, row := range board {
        for _, c := range row {
            switch {
            case c == -1:
                fmt.Print(" . ")
            case c > 0:
                fmt.Printf("%2d ", c)
            default:
                fmt.Print("__ ")
            }
        }
        fmt.Println()
    }
}

func main() {
    input := []string{
        "_ 33 35 _ _ . . .",
        "_ _ 24 22 _ . . .",
        "_ _ _ 21 _ _ . .",
        "_ 26 _ 13 40 11 . .",
        "27 _ _ _ 9 _ 1 .",
        ". . _ _ 18 _ _ .",
        ". . . . _ 7 _ _",
        ". . . . . . 5 _",
    }
    setup(input)
    printBoard()
    fmt.Println("\nFound:")
    solve(start[0], start[1], 1, 0)
    printBoard()
}


  

You may also check:How to resolve the algorithm Draw a clock step by step in the Quackery programming language
You may also check:How to resolve the algorithm Pig the dice game step by step in the Pascal programming language
You may also check:How to resolve the algorithm SOAP step by step in the Tcl programming language
You may also check:How to resolve the algorithm Nested function step by step in the SuperCollider programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Golo programming language