Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions n-queens-all.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include<bits/stdc++.h>
#include<iostream>

using namespace std;

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

void place_queens(vector<vector<int>> &board, int col, int n, vector<vector<vector<int>>> &ans) {

if(col == n) {
ans.push_back(board);
}
int i=0;
while(i < n) {
board[i][col] = 1;
if(check(board, i, col, n)) {
place_queens(board, col+1, n, ans);
}
board[i][col] = 0;
i++;
}
}

int main() {
int n;
cin >> n;
vector<vector<int>> board;
for(int i=0;i<n;i++) {
vector<int> temp(n, 0);
board.push_back(temp);
}
vector<vector<vector<int>>> ans;
place_queens(board, 0, n, ans);

if(ans.size() == 0) {
cout << "No solution is possible";
return 0;
}

for(int a=0;a<ans.size();a++) {
board = ans[a];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
cout << endl;
}

}
47 changes: 47 additions & 0 deletions optimalgame.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include<bits/stdc++.h>
using namespace std;

int solve(vector<int>& arr, vector<vector<int>> &ans, int i, int j)
{
// if (i < 0 || j >= arr.size())
// {
// return 0;
// }
// if (ans[i][j] != -1)
// return ans[i][j];
if(j == i)
return arr[i];
if (j == i+1)
{
ans[i][j] = max(arr[i], arr[j]);
return ans[i][j];
}
int temp = max(arr[i] + min(solve(arr, ans, i+2, j), solve(arr, ans, i+1, j-1)),
arr[j] + min(solve(arr, ans, i+1, j-1), solve(arr, ans, i, j-2)));
ans[i][j] = temp;
return ans[i][j];
}

int main()
{
int t;
cin >> t;
while (t--)
{
int n; int temp;
cin >> n;
vector<int> arr(n);
vector<vector<int>> ans(n,vector<int>(n,0));
for (int i=0;i<n;i++)
{
cin >> arr[i];
}
int res=solve(arr, ans, 0, n-1);
cout << res << endl;
}
}



// F(i, j) = Max(Vi + min(F(i+2, j), F(i+1, j-1) ),
// Vj + min(F(i+1, j-1), F(i, j-2) ))