M = 8; N = 8; board = matrix(0, nrow = M, ncol = N)


getboard = function (position)    { board[position[1], position[2]] }
setboard = function (position, x) { board[position[1], position[2]] <<- x }


hops = cbind(c(-2, -1), c(-1, -2), c(+1, -2), c(+2, -1),
             c(+2, +1), c(+1, +2), c(-1, +2), c(-2, +1))


valid = function (move) {
    all(1 <= move & move <= c(M, N)) && (getboard(move) == 0)
}


explore = function (position) {
    moves = position + hops
    cbind(moves[, apply(moves, 2, valid)])
}


candidates = function (position) {
    moves = explore(position)

    
    if (ncol(moves) == 0) { return(moves) }

    wcosts = apply(moves, 2, function (position) { ncol(explore(position)) })
    cbind(moves[, order(wcosts)])
}


knightTour = function (position, moveN) {

    
    if (moveN > (M * N)) {
        print(board)
        quit()
    }

    
    moves = candidates(position) 

    
    if (ncol(moves) == 0) { return() }

    
    apply(moves, 2, function (position) {
                        setboard(position, moveN)
                        knightTour(position, moveN + 1)
                        setboard(position, 0)
                    })
}


square = commandArgs(trailingOnly = TRUE)


row      = M + 1 - as.integer(substr(square, 2, 2))
ascii    = function (ch) { as.integer(charToRaw(ch)) }
col      = 1 + ascii(substr(square, 1, 1)) - ascii('a')
position = c(row, col)


setboard(position, 1); knightTour(position, 2)