about summary refs log blame commit diff stats
path: root/awk/nqueens.awk
blob: 1baef8ee9b563c495edcb9aa6285256d4c4de0e6 (plain) (tree)
1
2
3
4
5
6
7
8
9




                     


                                         
                                                                                           
                                                                                        
                                                                                        

         
                               


















                                  
                                                                 












                                          
                                        
                      
 
# run with: 
#  awk -f nqueens.awk
# mawk -f nqueens.awk
# etc.

# Check if a position is safe for a queen
function is_safe(board, row, col, N) {
    for (i = 1; i < row; i++) {
        # Check if there is a queen in the same column or diagonals as the current position
        if (board[i] == col || board[i] - i == col - row || board[i] + i == col + row) {
            return 0  # Oh no! Not safe! There is a queen attacking the current position
        }
    }
    return 1  # Safe! No queens
}

# Print the board configuration
function print_board(board, N) {
    for (i = 1; i <= N; i++) {
        for (j = 1; j <= N; j++) {
            if (board[i] == j) {
                printf "Q "
            } else {
                printf ". "
            }
        }
        printf "\n"
    }
    printf "\n"
}

function solve(board, row, N) {
    if (row > N) {
        # Display the state of the board when a solution is found
        print_board(board, N)
        return
    }

    for (col = 1; col <= N; col++) {
        if (is_safe(board, row, col, N)) {
            board[row] = col
            solve(board, row + 1, N)
        }
    }
}

BEGIN {
    N = 10  # Sets the size of the board
    solve(board, 7, N)
}