HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Project Euler #15 -- count possible lattice paths

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pathslatticeprojectpossibleeulercount

Problem

I'm not a C programmer, just wanted to make a fast solution to the problem.


Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

How many such routes are there through a 20×20 grid?

Here's my code:

```
#include
#define SIZE 21 // grid size + 1

long long int count_routes(long long int cache[SIZE][SIZE], unsigned short x, unsigned short y) {

if (cache[x][y] != 0) {
return cache[x][y];
}

long long int n = 0;

if (x == 0 && y == 0) {
n = 1;
}
else {
n = 0;

Solution

I do not know whether my suggestion makes code faster, but it sure does make it shorter and probably equally fast. It calculates the possibilities dynamically, using the observation that number of ways to get to a square is the sum of numbers of ways to get to the top and the left square, as does yours, but it does not use recursion, so it's perhaps easier to understand or code.

#include 

unsigned long long g[21][21];

int main() { 
    for (int i = 0; i < 21; ++i) {
        g[i][0] = 1;
        g[0][i] = 1;
    }
    for (int i = 1; i < 21; ++i) {
        for (int j = 1; j < 21; ++j) {
            g[i][j] = g[i-1][j] + g[i][j-1];
        }
    }

    printf("%lld\n", g[20][20]);
    return 0;
}

Code Snippets

#include <cstdio>

unsigned long long g[21][21];

int main() { 
    for (int i = 0; i < 21; ++i) {
        g[i][0] = 1;
        g[0][i] = 1;
    }
    for (int i = 1; i < 21; ++i) {
        for (int j = 1; j < 21; ++j) {
            g[i][j] = g[i-1][j] + g[i][j-1];
        }
    }

    printf("%lld\n", g[20][20]);
    return 0;
}

Context

StackExchange Code Review Q#25419, answer score: 4

Revisions (0)

No revisions yet.