N-Queens

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

Example:

Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<vector<string>> ans;

bool isValid(vector<string&currint rint c)
{
    for (int i = ri >= 0i--)
    {
        if (curr[i][c] == 'Q')
            return false;
    }
    for (int i = rj = ci >= 0 && j >= 0i--, j--)
    {
        if (curr[i][j] == 'Q')
            return false;
    }
    for (int i = rj = ci >= 0 && j < curr.size(); i--, j++)
    {
        if (curr[i][j] == 'Q')
            return false;
    }
    return true;
}

void dfs(vector<string&currint r)
{
    if (curr.size() == r)
    {
        ans.push_back(curr);
        return;
    }
    for (int i = 0i < curr.size(); i++)
    {
        if (isValid(currri))
        {
            curr[r][i] = 'Q';
            dfs(currr + 1);
            curr[r][i] = '.';
        }
    }
}

vector<vector<string>> solveNQueens(int n)
{
    vector<stringcurr(nstring(n'.'));
    dfs(curr0);
    return ans;
}

int main()
{
    int n = 4;

    vector<vector<string>> queens = solveNQueens(n);

    cout << "[";
    for (int i = 0i < queens.size(); i++)
    {
        cout << "[";
        for (int j = 0j < queens[i].size(); j++)
        {
            cout << queens[i][j];
            if (j != queens[i].size() - 1)
                cout << ", ";
        }
        cout << "]";
        if (i != queens.size() - 1)
            cout << ", ";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment