about summary refs log tree commit diff stats
path: root/awk/nqueens.awk
blob: 1baef8ee9b563c495edcb9aa6285256d4c4de0e6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 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)
}