N Queen recursive program - algorithm

I am trying to solve the n-queen problem (placing n queens on a nxn board without any two queens attacking each other) by defining a function that takes an nxn boolean array of falses and should fill the answer with true where the queens should be. I am getting incorrect answer but can't see why the recursion doesn't work!
bool check(bool ** board, int n, int row, int col){
if(row == 0) return true;
for(int r = 0 ; r < row ; ++r){
if(board[r][col]) return false;
int left = max(col - row + r, 0), right = min(col + row - r, n-1);
if(board[r][left] || board[r][right]) return false;
}
return true;
}
bool queen(bool ** board, int n, int level = 0 ){
for(int col = 0 ; col < n ; ++col){
if( !check(board, n, level, col) ) continue;
board[ level ][ col ] = true;
if( level == n-1 ) return true;
if( queen(board, n, level+1) ) return true;
board[ level ][ col ] = false;
}
return false;
}
in main() i dynamically create bool ** board, and fill it with false, then call queen(board, n).
The weird thing is that it is giving the correct solution except for n=4,6!
Any help is greatly appreciated!

Your fault is the min/max.Operation, so you don't check straight lines.
This should do the trick:
int left = col - row + r;
int right = col + row - r;
if ( left >= 0 && board[r][left] || right < n && board[r][right])
return false;

Related

How do I convert this recursion to dp

I am trying to solve this problem. I believe my solution does work, but it takes more time. This is my solution - at each step, I calculate the minimum sum if I choose i or i+1 index.
class Solution
{
public int minimumTotal(List<List<Integer>> triangle)
{
return minSum( triangle, 0, 0 );
}
public int minSum( List<List<Integer>> triangle, int row, int index )
{
if( row >= triangle.size() )
return 0;
int valueAtThisRow = triangle.get(row).get(index);
return Math.min( valueAtThisRow + minSum(triangle, row+1, index),
valueAtThisRow + minSum(triangle, row+1, index+1));
}
}
I think more appropriate way is to use DP. Please share any suggestions on how I can convert this to a DP.
I think that bottom-up solution is simpler here and does not require additional memory, we can store intermediate results in the same list/array cells
Walk through levels of triangle starting from the level before last, choosing the best result from two possible for every element, then move to upper level and so on. After that triangle[0][0] will contain minimum sum
for (row = n - 2; row >= 0; row--)
for (i = 0; i <= row; i++)
triangle[row][i] += min(triangle[row+1][i], triangle[row+1][i+1])
(tried python version, accepted)
DP bottom up approach:
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle)
{
vector<int> mini = triangle[triangle.size()-1];
for ( int i = triangle.size() - 2; i>= 0 ; --i )
for ( int j = 0; j < triangle[i].size() ; ++ j )
mini[j] = triangle[i][j] + min(mini[j],mini[j+1]);
return mini[0];
}
};
Python version:
def minimumTotal(self, triangle: List[List[int]]) -> int:
if not triangle: return
size = len(triangle)
res = triangle[-1] # last row
for r in range(size-2, -1, -1): # bottom up
for c in range(len(triangle[r])):
res[c] = min(res[c], res[c+1]) + triangle[r][c]
return res[0]
Top down solution: we compute shortest paths (agenda) to each cells row by row starting from the triangle's top.
C# code
public int MinimumTotal(IList<IList<int>> triangle) {
int[] agenda = new int[] {triangle[0][0]};
for (int r = 1; r < triangle.Count; ++r) {
int[] next = triangle[r].ToArray();
for (int c = 0; c < next.Length; ++c)
if (c == 0)
next[c] += agenda[c];
else if (c == next.Length - 1)
next[c] += agenda[c - 1];
else
next[c] += Math.Min(agenda[c - 1], agenda[c]);
agenda = next;
}
return agenda.Min();
}

Develop an algorithm

I participated in a programming competition at my University. I solved all the questions except this one. Now I am practicing this question to improve my skills. But I can't figure out the algorithm. If there is any algorithm existing please update me. Or any similar algorithm is present then please tell me I will change it according to this question.
This is what I want to do.
The First line of input is the distance between two points.
After that, each subsequent line contains a pair of numbers indicating the length of cable and quantity of that cable. These cables are used to join the two points.
Input is terminated by 0 0
Output:
The output should contain a single integer representing the minimum number of joints possible to build the requested length of cableway. If no solution possible than print "No solution".
Sample Input
444
16 2
3 2
2 2
30 3
50 10
45 12
8 12
0 0
Sample Output
10
Thanks guys. I found a solution from "Perfect subset Sum" problem and then made a few changes in it. Here's the code.
#include <bits/stdc++.h>
using namespace std;
bool dp[100][100];
int sizeOfJoints = -1;
void display(const vector<int>& v)
{
if (sizeOfJoints == -1)
{
sizeOfJoints = v.size() - 1;
}
else if (v.size()< sizeOfJoints)
{
sizeOfJoints = v.size() - 1;
}
}
// A recursive function to print all subsets with the
// help of dp[][]. Vector p[] stores current subset.
void printSubsetsRec(int arr[], int i, int sum, vector<int>& p)
{
// If sum becomes 0
if (sum == 0)
{
display(p);
return;
}
if(i<=0 || sum<0)
return;
// If given sum can be achieved after ignoring
// current element.
if (dp[i-1][sum])
{
// Create a new vector to store path
//vector<int> b = p;
printSubsetsRec(arr, i-1, sum, p);
}
// If given sum can be achieved after considering
// current element.
if (sum >= arr[i-1] && dp[i-1][sum-arr[i-1]])
{
p.push_back(arr[i-1]);
printSubsetsRec(arr, i-1, sum-arr[i-1], p);
p.pop_back();
}
}
// all subsets of arr[0..n-1] with sum 0.
void printAllSubsets(int arr[], int n, int sum)
{
if (n == 0 || sum < 0)
return;
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// If sum is not 0 and set is empty, then answer is false
for (int i = 1; i <= sum; i++)
dp[0][i] = false;
// Fill the subset table in botton up manner
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if(j<arr[i-1])
dp[i][j] = dp[i-1][j];
if (j >= arr[i-1])
dp[i][j] = dp[i-1][j] ||
dp[i - 1][j-arr[i-1]];
}
}
if (dp[n][sum] == false)
{
return;
}
// Now recursively traverse dp[][] to find all
// paths from dp[n-1][sum]
vector<int> p;
printSubsetsRec(arr, n, sum, p);
}
// Driver code
int main()
{
int input[2000];
int inputIndex = 0;
int i = 0;
int distance = 0;
cout<< "Enter Input: " <<endl;
cin>> distance;
while(true)
{
int temp1 = 0;
int temp2 = 0;
cin>> temp1;
cin>> temp2;
if (temp1 == 0 && temp2 == 0)
{
break;
}
for (i = 0; i < temp2; i++)
input[inputIndex++] = temp1;
}
cout<< "Processing output. Please wait: " <<endl;
printAllSubsets(input, inputIndex, distance);
if(sizeOfJoints != -1)
cout<<sizeOfJoints;
else
cout<<"No Solution Possible";
return 0;
}

count paths from source to destination in a matrix moving in all 4 directions

Say, I have a matrix of size n*n and I want to traverse from 0,0 to n-1,n-1 if I'm allowed to move in all four directions - right,left,up and down. How do I find all paths using recursion.
Below is my approach for doing this given you're allowed to move in only 2 directions - right and down.
static int findWays2directions( int[][] a, int i, int j ) {
if ( i < 0 || j < 0 || i == a.length || j == a[0].length )
return 0;
if ( i == a.length - 1 && j == a[0].length - 1 )
return 1;
int right = findWays2directions( a, i, j + 1 );
int down = findWays2directions( a, i + 1, j );
return right + down;
}
However, when allowed to move in all four directions, this does not work, if I were to add the additional recursive steps to the left and up. This is due to the fact that cycles are generated, as in going from 0,1 to 0,0 and then back to 0,0 leading to an infinite loop. I have tried to avoid this by maintaining a visited two-dimensional array, and returning 0 if already visited. However, I don't think that gives me the correct output since the problem is to count paths, and not just do a traversal.
static int findWays4directions( int[][] a, int i, int j, boolean[][] visited ) {
if ( i < 0 || j < 0 || i == a.length || j == a[0].length )
return 0;
if ( i == a.length - 1 && j == a[0].length - 1 )
return 1;
if ( visited[i][i] == true )
return 0;
visited[i][j] = true;
int right = findWays4directions( a, i, j + 1, visited );
int down = findWays4directions( a, i + 1, j, visited );
int left = findWays4directions( a, i, j - 1, visited );
int up = findWays4directions( a, i - 1, j, visited );
return left + down + right + up;
}
How can I count all paths from source to destination in a matrix moving in all 4 directions
Try setting visited[i][j] = false when exiting a cell. But beware: this is not a dynamic programming solution (I'm convinced that there is no DP solution to this problem). Instead, you're doing an unbounded search (a kind of backtracking):
Also: fixed the bug if (visited[i][i]) ... in your code.
static int findWays4directions( int[][] a, int i, int j, boolean[][] visited ) {
if ( i < 0 || j < 0 || i == a.length || j == a[0].length )
return 0;
if ( i == a.length - 1 && j == a[0].length - 1 )
return 1;
if ( visited[i][j] == true )
return 0;
visited[i][j] = true;
int right = findWays4directions( a, i, j + 1, visited );
int down = findWays4directions( a, i + 1, j, visited );
int left = findWays4directions( a, i, j - 1, visited );
int up = findWays4directions( a, i - 1, j, visited );
visited[i][j] = false;
return left + down + right + up;
}
Agree with the dfs algorithm, however the base case check need add visited[i][j] to check the duplicated visit.
if (i < 0 || i >= n || j < 0 || j >= n || visited[i][j]) {
return 0;
}

Numbrix Generator Algorithm

I'd been trying to program a Numbrix generator with two conditions:
Square grid 10 x 10
Number 1 is on the bottom row of the grid and 100 on the top row
Rules of Numbrix are that every number must have a side (in the grid) in common with the following number.
I'd been trying to make an algorithm that generates a random grid that satisfies what I said and I'd been unable of doing so. My main attempt was to simply keep trying a path randomly, going back when needed, until I ended up with a path that finished with 100 on top row, but that seemed to be too inefficient.
I hoped to find here a guideline on how to build such algorithm.
I'd been trying to do so in C++, but since the main issue here is the algorithm, language shouldn't be the issue.
Here's my algorithm right now:
int nrow = 10;
int ncol = 10;
typedef vector< vector<int> > matrix;
bool generate_path(int x, int y, matrix &grid, int value, int maxused)
{
if(x == 0) maxused++;
if(maxused == ncol && value != nrow*ncol) return(false);
grid[x][y] = value;
if(grid[x][y] == nrow * ncol)
{
if(x == 0) return(true);
grid[x][y] = 0;
return(false);
}
// 0: North, 1: East, 2: South, 3: West
bool directions[4];
directions[0] = y+1 < ncol && grid[x][y+1] == 0;
directions[1] = x+1 < nrow && grid[x+1][y] == 0;
directions[2] = y > 0 && grid[x][y-1] == 0;
directions[3] = x > 0 && grid[x-1][y] == 0;
while(directions[0] || directions[1] || directions[2] || directions[3])
{
int direction = rand() % 4;
while(!directions[direction]) direction = rand() % 4;
switch(direction)
{
case 0:
if(generate_path(x, y+1, grid, value+1, maxused)) return(true);
directions[direction] = false;
break;
case 1:
if(generate_path(x+1, y, grid, value+1, maxused)) return(true);
directions[direction] = false;
break;
case 2:
if(generate_path(x, y-1, grid, value+1, maxused)) return(true);
directions[direction] = false;
break;
case 3:
if(generate_path(x-1, y, grid, value+1, maxused)) return(true);
directions[direction] = false;
break;
}
}
grid[x][y] = 0;
return(false);
}
matrix generate_grid(const int &mult)
{
matrix grid(nrow, vector<int> (ncol, 0));
int x = nrow-1;
int y = rand() % ncol;
generate_path(x, y, grid, 1, 0);
for(int i = 0; i < nrow; i++) for(int j = 0; j < ncol; j++) grid[i][j] = grid[i][j] * mult;
return grid;
}
When I do Numbrix, I've noticed that the numbers are usually in random places, but there is always a bridge of numbers to get to the other number, and there are no blockages.
You could just write out a Numbrix yourself on paper instead of trying to figure it out on the computer. Or, you could look up Numbrix and write down theirs, but alter it a little to your own liking. Hope this helps!

Segment tree with lazy propagation for multiple of 3

Abridged problem: You're given an array of n elements, initially they are all 0.
You will receive two types of query: 0 index1 index2, in this case you have to increase by one all elements in range index1 index2(included).
Second type: 1 index1 index2, in this case you have to print a number rapresenting how many elements between index1 and index2(included) are divisible by 3.
Of course, as n is very large(10^6) the good approach is to use segment tree to store intervals, and also to use lazy propagation to update the tree in log n.
But I actually really don't know how to apply lazy propagation here, because you have to keep into account three possible states for every number( may be 3k,3k+1,3k+2), and not just two as the flipping coins problem.
If I put a flag on some interval that is included in the interval of my query, I have to update it looking at the original array and at its value, but when I have to update the son of this interval I have to do the same again and this is a wasteful of time....
Any better idea? I search on the net but found nothing ...
EDIT: I follow your suggestions and I code this( C++), and works for some base cases, but when I submit it I get just 10/100 points, what is wrong with it ? (I know it's a bit long and there are no much comments but it's a simple Segment Tree with lazy propagation, if you don't understand something, please tell me!
NOTE: st[p].zero contains elements that are 0 mod 3 in interval stored in index p, st[p].one elements 1 mod 3, and st[p].two elements 2 mod 3; When I update I shift of one position these elements(0->1, 1->2, 2->0) and I use lazy. On updating, I return a pair < int , pair< int, int > >, just a simple way to store a triple of numbers, In this way a can return the difference of numbers 0,1,2 mod 3.
int sol;
struct mod{
mod(){ zero=0; one=0;two=0;}
int zero;
int one;
int two;
};
class SegmentTree {
public: int lazy[MAX_N];
mod st[MAX_N];
int n;
int left (int p) { return p << 1; }
int right(int p) { return (p << 1) + 1; }
void build(int p, int L, int R){
if(L == R)
st[p].zero=1;
else{
st[p].zero = R - L + 1;
build(left(p), L, (L + R) / 2);
build(right(p), ((L + R) / 2) + 1, R);
}
return;
}
void query(int p, int L, int R, int i, int j) {
if (L > R || i > R || j < L) return;
if(lazy[p]!=0){ // Check if this no has to be updated
for(int k=0;k<lazy[p];k++){
swap(st[p].zero,st[p].two);
swap(st[p].one, st[p].two);
}
if(L != R){
lazy[left(p)] = (lazy[left(p)] + lazy[p]) % 3;
lazy[right(p)] = (lazy[right(p)] + lazy[p]) % 3;
}
lazy[p] = 0;
}
if (L >= i && R <= j) { sol += st[p].zero; return; }
query(left(p) , L , (L+R) / 2, i, j);
query(right(p), (L+R) / 2 + 1, R , i, j);
return;
}
pair < int, ii > update_tree(int p, int L, int R, int i, int j) {
if (L > R || i > R || j < L){
pair< int, pair< int, int > > PP; PP.first=PP.second.first=PP.second.second=INF;
return PP;
}
if(lazy[p]!=0){ // Check if this no has to be updated
for(int k=0;k<lazy[p];k++){
swap(st[p].zero,st[p].two);
swap(st[p].one, st[p].two);
}
if(L != R){
lazy[left(p)] = (lazy[left(p)] + lazy[p]) % 3;
lazy[right(p)] = (lazy[right(p)] + lazy[p]) % 3;
}
lazy[p] = 0;
}
if(L>=i && R<=j){
swap(st[p].zero, st[p].two);
swap(st[p].one, st[p].two);
if(L != R){
lazy[left(p)] = (lazy[left(p)] + 1) % 3;
lazy[right(p)] = (lazy[right(p)] + 1) % 3;
}
pair< int, pair< int, int > > t; t.first = st[p].zero-st[p].one; t.second.first = st[p].one-st[p].two; t.second.second = st[p].two-st[p].zero;
return t;
}
pair< int, pair< int, int > > s = update_tree(left(p), L, (L+R)/2, i, j); // Updating left child
pair< int, pair< int, int > > s2 = update_tree(right(p), 1+(L+R)/2, R, i, j); // Updating right child
pair< int, pair< int, int > > d2;
d2.first = ( (s.first!=INF ? s.first : 0) + (s2.first!=INF ? s2.first : 0) ); // Calculating difference from the ones given by the children
d2.second.first = ( (s.second.first!=INF ? s.second.first : 0) + (s2.second.first!=INF ? s2.second.first : 0) );
d2.second.second = ( (s.second.second!=INF ? s.second.second : 0) + (s2.second.second!=INF ? s2.second.second : 0) );
st[p].zero += d2.first; st[p].one += d2.second.first; st[p].two += d2.second.second; // Updating root
return d2; // Return difference
}
public:
SegmentTree(const vi &_A) {
n = (int)_A.size();
build(1, 0, n - 1);
}
void query(int i, int j) { return query(1, 0, n - 1, i, j); }
pair< int, pair< int, int > > update_tree(int i, int j) {
return update_tree(1, 0, n - 1, i, j); }
};
int N,Q;
int main() {
FILE * in; FILE * out;
in = fopen("input.txt","r"); out = fopen("output.txt","w");
fscanf(in, "%d %d" , &N, &Q);
//cin>>N>>Q;
int arr[N];
vi A(arr,arr+N);
SegmentTree *st = new SegmentTree(A);
for(int i=0;i<Q;i++){
int t,q,q2;
fscanf(in, "%d %d %d " , &t, &q, &q2);
//cin>>t>>q>>q2;
if(q > q2) swap(q, q2);
if(t){
sol=0;
st->query(q,q2);
fprintf(out, "%d\n", sol);
//cout<<sol<<endl;
}
else{
pair<int, pair< int, int > > t = st->update_tree(q,q2);
}
}
fclose(in); fclose(out);
return 0;
}
You can store two values in each node:
1)int count[3] - how many there are 0, 1 and 2 in this node's segment.
2)int shift - shift value(initially zero).
The operations are performed in the following way(I use pseudo code):
add_one(node v)
v.shift += 1
v.shift %= 3
propagate(node v)
v.left_child.shift += v.shift
v.left_child.shift %= 3
v.right_child.shift += v.shift
v.right_child.shift %= 3
v.shift = 0
for i = 0..2:
v.count[i] = get_count(v.left, i) + get_count(v.right, i)
get_count(node v, int remainder)
return v.count[(remainder + v.shift) % 3]
The number of elements divisible by 3 for a node v is get_count(v, 0).
Update for a node is add_one operation. In general, it can be used as an ordinary segment tree(to answer range queries).
The entire tree update looks like that:
update(node v, int left, int right)
if v is fully covered by [left; right]
add_one(v)
else:
propagate(v)
if [left; right] intersects with the left child:
update(v.left, left, right)
if[left; right] intersects with the right child:
update(v.right, left, right)
for i = 0..2:
v.count[i] = get_count(v.left, i) + get_count(v.right, i)
Getting the number of elements divisible by 3 is done in similar manner.
It seems that you never have to care about the values of the elements, only their values modulo 3.
Keep a segment tree, using lazy updates as you suggest. Each node knows the number of things that are 0, 1, and 2 modulo 3 (memoization).
Each update hits log(n) nodes. When an update hits a node, you remember that you have to update the descendants (lazy update) and you cycle the memoized number of things in the subtree that are 0, 1, and 2 modulo 3.
Each query hits log(n) nodes; they're the same nodes an update of the same interval would hit. Whenever a query comes across a lazy update that hasn't been done, it pushes the update down to the descendants before recursing. Apart from that, all it does is it adds up the number of elements that are 0 modulo 3 in each maximal subtree completely contained in the query interval.

Resources