Graph Theory37 sections · 1633 units
Open in Course

Knight's Tour - Implementation

Code walkthrough.

function knightsTour(startRow, startCol):
    visited = 8x8 array of false
    path = [(startRow, startCol)]
    visited[startRow][startCol] = true

    function countMoves(r, c):
        count = 0
        for each knight move (dr, dc):
            nr = r + dr
            nc = c + dc
            if valid(nr, nc) and not visited[nr][nc]:
                count = count + 1
        return count

    function solve():
        if path.length == 64:
            return true
        r, c = path.last()
        // Sort moves by Warnsdorff's heuristic
        moves = [(countMoves(nr, nc), nr, nc) for valid unvisited neighbors]
        sort moves by first element (ascending)
        for each (_, nr, nc) in moves:
            visited[nr][nc] = true
            path.append((nr, nc))
            if solve():
                return true
            path.pop()
            visited[nr][nc] = false
        return false

    solve()
    return path

This runs in O(8n2)O(8^{n^2}) time and uses O(n2)O(n^2) space.