I'm trying to count total paths in a 20x20 grid(ProjectEuler #15) using backtracking.I've played around with it but the answer is always None. Any help would be appreciated(I know it can be solved using recursion or memoization but i want to solve it using backtracking)
def isvalid(maze,n,x,y):
if x<0 or y<0 or x>n or y>n :
return False
else: return True
def countPaths(maze,x,y,n,used,count):
if x==n-1 or y==n-1:
count+=1
return
if isvalid(maze,n,x,y):
used[x][y]=True
if (x+1<n and used[x+1][y]==False):
countPaths(maze,x+1,y,n,used,count)
if (x-1>0 and used[x-1][y]==False):
countPaths(maze,x-1,y,n,used,count)
if (y+1<n and used[x][y+1]==False):
countPaths(maze,x,y+1,n,used,count)
if (y-1>0 and used[x][y-1]==False):
countPaths(maze,x,y-1,n,used,count)
used[x][y]=False
return
Since in the base case, you are only returning 1 whenever end of row or column occurs it would yield wrong answer.
You should increment a counter signifying the number of times you are able to reach the final [n-1][n-1] i.e rightmost bottom cell.
bool isValid(int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= n)
return false;
return true;
}
void countPaths(int x, int y)
{
// cout << x << y << endl;
if (x == n - 1 && y == n - 1)
{
paths++;
return;
}
if (isValid(x, y))
{
visited[x][y] = true;
countPaths(x, y + 1);
countPaths(x + 1, y);
}
return;
}
Keeping paths & visited as global variables , I implemented the above approach.
For n=2 (1+1): 2
For n=3 (2+1): 6
For n=4 (3+1): 20
For n=5 (4+1): 70
however, this approach would not be viable for n=20.
I would suggest trying Dynamic Programming as it would simplify the process!
Related
I have got a code that generates all possible correct strings of balanced brackets. So if the input is n = 4 there should be 4 brackets in the string and thus the answers the code will give are: {}{} and
{{}}.
Now, what I would like to do is print the number of possible strings. For example, for n = 4 the outcome would be 2.
Given my code, is this possible and how would I make that happen?
Just introduce a counter.
// Change prototype to return the counter
int findBalanced(int p,int n,int o,int c)
{
static char str[100];
// The counter
static int count = 0;
if (c == n) {
// Increment it on every printout
count ++;
printf("%s\n", str);
// Just return zero. This is not used anyway and will give
// Correct result for n=0
return 0;
} else {
if (o > c) {
str[p] = ')';
findBalanced(p + 1, n, o, c + 1);
}
if (o < n) {
str[p] = '(';
findBalanced(p + 1, n, o + 1, c);
}
}
// Return it
return count;
}
What you're looking for is the n-th Catalan number. You'll need to implement binomial coefficient to calculate it, but that's pretty much it.
I've several confusion about tail recursion as follows:
some of the recursion functions are void functions for example,
// Prints the given number of stars on the console.
// Assumes n >= 1.
void printStars(int n) {
if (n == 1) {
// n == 1, base case
cout << "*";
} else {
// n > 1, recursive case
cout << "*"; // print one star myself
printStars(n - 1); // recursion to do the rest
}
}
and another example:
// Prints the given integer's binary representation.
// Precondition: n >= 0
void printBinary(int n) {
if (n < 2) {
// base case; same as base 10
cout << n;
} else {
// recursive case; break number apart
printBinary(n / 2);
printBinary(n % 2);
}
}
As we know by definition tail recursion should return some value from tail call. But for void functions it does not return any value. By intinction I think they are tail recursion but I am not confident about it.
another question is that, if a recursion function has several logical end, should tail recursion come at all logical ends or just one of the logical ends? I saw someone argued that only one of the logical ends is OK, but I am not sure about that. Here's my example:
// Returns base ^ exp.
// Precondition: exp >= 0
int power(int base, int exp) {
if (exp < 0) {
throw "illegal negative exponent";
} else if (exp == 0) {
// base case; any number to 0th power is 1
return 1;
} else if (exp % 2 == 0) {
// recursive case 1: x^y = (x^2)^(y/2)
return power(base * base, exp / 2);
} else {
// recursive case 2: x^y = x * x^(y-1)
return base * power(base, exp - 1);
}
}
Here we have logical end as tail recursion and another one that is not tail recursion. Do you think this function is tail recursion or not? why?
In this recursive method, I am trying to calculate a number using the initial call mystery5(-23, -48). After going through my first series of if statements, I get to the numbers 23 and 48. Once I get to the else branch of the decision statements, what precedence does the method call have in the equation? Also, does a negative sign in front of the mystery5 method call in the first two if statements indicate that there will be a positive x value if -23 is inserted into the method call (Ex: -mystery5(-23, -48))?
public int mystery5(int x, int y){
if (x < 0) {
return -mystery5(-x, y);
} else if (y < 0) {
return -mystery5(x, -y);
} else if (x == 0 && y == 0) {
return 0;
} else {
return 100 * mystery5(x / 10, y / 10) + 10 * (x % 10) + y % 10;
}
}
So it looks to me that mystery5(1, 0) returns 1. Assuming that is correct, then the call mystery5(-1, 0) would hit that first statement and it would see that x = -1) which is less than zero. This does return -mystery5(-x,y), so when the values for x and y are put in, this is equivalent to return -mystery5(1,0). The - in front of mystery5 flips the sign on the result of the mystery5 function when called. So when mystery5(1,0) returns a 1, that gets negated to -1. And that is the final return value of mystery5(-1,0).
I've got the following grid of numbers centered around 0 and increasing in spiral. I need an algorithm which would receive number in spiral and return x; y - numbers of moves how to get to that number from 0. For example for number 9 it would return -2; -1. For 4 it would be 1; 1.
25|26|... etc.
24| 9|10|11|12
23| 8| 1| 2|13
22| 7| 0| 3|14
21| 6| 5| 4|15
20|19|18|17|16
This spiral can be slightly changed if it would help the algorithm to be better.
Use whatever language you like. I would really appreciate mathematical explanation.
Thank you.
First we need to determine which cycle (distance from center) and sector (north, east, south or west) we are in. Then we can determine the exact position of the number.
The first numbers in each cycle is as follows: 1, 9, 25
This is a quadratic sequence: first(n) = (2n-1)^2 = 4n^2 - 4n + 1
The inverse of this is the cycle-number: cycle(i) = floor((sqrt(i) + 1) / 2)
The length of a cycle is: length(n) = first(n+1) - first(n) = 8n
The sector will then be:
sector(i) = floor(4 * (i - first(cycle(i))) / length(cycle(i)))
Finally, to get the position, we need to extrapolate from the position of the first number in the cycle and sector.
To put it all together:
def first(cycle):
x = 2 * cycle - 1
return x * x
def cycle(index):
return (isqrt(index) + 1)//2
def length(cycle):
return 8 * cycle
def sector(index):
c = cycle(index)
offset = index - first(c)
n = length(c)
return 4 * offset / n
def position(index):
c = cycle(index)
s = sector(index)
offset = index - first(c) - s * length(c) // 4
if s == 0: #north
return -c, -c + offset + 1
if s == 1: #east
return -c + offset + 1, c
if s == 2: #south
return c, c - offset - 1
# else, west
return c - offset - 1, -c
def isqrt(x):
"""Calculates the integer square root of a number"""
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
while True:
y = (x + n//x)//2
if y >= x:
return x
x = y
Example:
>>> position(9)
(-2, -1)
>>> position(4)
(1, 1)
>>> position(123456)
(-176, 80)
Do you mean something like this? I did not implement any algorithm and the code can be written better but it works - that's always a start :) Just change the threshold value for whatever you wish and you'll get the result.
static int threshold=14, x=0, y=0;
public static void main(String[] args) {
int yChange=1, xChange=1, count=0;
while( !end(count) ){
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y--;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x++;
}
xChange++;
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y++;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x--;
}
xChange++;
}
}
public static boolean end(int count){
if(count<threshold){
return false;
}else{
System.out.println("count: "+count+", x: "+x+", y: "+y);
return true;
}
}
If I know the number number y and know that 2^x=y, how do I compute x?
Base 2 logarithm function:
log2(y)
which is equivalent to:
log(y) / log(2)
for arbitrary base.
And in case you don't have a log function handy, you can always see how many times you must divide y by 2 before it becomes 1. (This assumes x is positive and an integer.)
If you are sure that it is a power of 2, then you can write a loop and right shift the number until you get a 1. The number of times the loop ran will be the value of x.
Example code:
int power(int num)
{
if(0 == num)
{
return 0;
}
int count = 0;
do
{
++count;
num = num >> 1;
}while(! (num & 1) && num > 0);
return count;
}
If x is a positive integer, then, following code will be more efficient..
unsigned int y; // You know the number y for which you require x..
unsigned int x = 0;
while (y >>= 1)
{
x++;
}
x is the answer!