about summary refs log tree commit diff stats
path: root/awk/nqueens.awk
blob: a42653751ea27d1120af6e3319b0382eca377a94 (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
# Check if a position is safe for a queen
function is_safe(board, row, col, N) {
    for (i = 1; i < row; i++) {
        # Check column and diagonals
        if (board[i] == col || board[i] - i == col - row || board[i] + i == col + row) {
            return 0
        }
    }
    return 1
}

# 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)
}