• + 0 comments

    N queen Problem

    include

    include

    using namespace std;

    bool isSafe(vector>& board, int row, int col, int n) { for (int i = 0; i < row; ++i) { if (board[i][col] == 1) return false; if (col - (row - i) >= 0 && board[i][col - (row - i)] == 1) return false; if (col + (row - i) < n && board[i][col + (row - i)] == 1) return false; } return true; }

    void solveNQueensUtil(vector>& board, int row, int n) { if (row == n) { for (auto& row : board) { for (int cell : row) { cout << (cell == 1 ? "Q " : "- "); } cout << endl; } cout << endl; return; }

    for (int col = 0; col < n; ++col) {
        if (isSafe(board, row, col, n)) {
            board[row][col] = 1;
            solveNQueensUtil(board, row + 1, n);
            board[row][col] = 0;
        }
    }
    

    }

    int main() { int n; cin >> n;

    vector<vector<int>> board(n, vector<int>(n, 0));
    solveNQueensUtil(board, 0, n);
    
    return 0;
    

    }