This code solves the N-Queens problem for a given value...

April 23, 2024 at 05:37 AM

#include <stdio.h> #define MAX 10 int is_attack(int row, int col, int n, int board[][MAX]) { int i, j; for (i = 0; i < row; i++) { if (board[i][col]) return 1; for (j = 0; j < n; j++) { if (board[i][j] && (i-j == row-col || i+j == row+col)) return 1; } } return 0; } int n_queens(int row, int n, int board[][MAX]) { int i, res = 0; if (row == n) return 1; for (i = 0; i < n; i++) { board[row][i] = 1; if (!is_attack(row, i, n, board)) { res += n_queens(row+1, n, board); } board[row][i] = 0; } return res; } int main() { int n, i, j, board[MAX][MAX] = {0}; printf("Enter the value of n: "); scanf("%d", &n); int res = n_queens(0, n, board); if (res == 0) printf("There is no solution for this problem\n"); else printf("There are %d solutions for this problem\n", res); return 0; }

This code solves the N-Queens problem for a given value of n, where n represents the size of the chessboard (n x n). The program finds and prints the number of possible solutions to place n queens on an n x n chessboard such that no two queens attack each other.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node