diff --git a/problem15/problem15 b/problem15/problem15 index 69a7ae0..dd5448e 100755 Binary files a/problem15/problem15 and b/problem15/problem15 differ diff --git a/problem15/problem15.cpp b/problem15/problem15.cpp index cad61f6..3c59f8e 100644 --- a/problem15/problem15.cpp +++ b/problem15/problem15.cpp @@ -1,28 +1,45 @@ #include -#include +#include using namespace std; -const int N = 2; +#define N 20 -int i, A[ 2*N ]; +long int** C, i, j; -int main() { - for ( i = 0; i < N; ++i ) { - A[ i ] = 0; - A[ i + N ] = 1; +long int CountRoutes( int x, int y ) { + if ( x == 0 && y == 0 ) { + return 1; } + long int cost = 0; + if ( y > 0 ) { + if ( C[ x ][ y - 1 ] == -1 ) { + C[ x ][ y - 1 ] = CountRoutes( x, y - 1 ); + } - i = 1; - while ( next_permutation( A, A + 2 * N ) ) { - for ( i = 0; i < 2 * N; ++i ) { - printf( "%i ", A[ i ] ); + cost += C[ x ][ y - 1 ]; + } + if ( x > 0 ) { + if ( C[ x - 1 ][ y ] == -1 ) { + C[ x - 1 ][ y ] = CountRoutes( x - 1, y ); } - printf( "\n" ); - ++i; + + cost += C[ x - 1 ][ y ]; } - printf( "Solution: %i\n", i ); + return cost; +} + +int main() { + C = ( long int** )malloc( ( N + 1 ) * sizeof( long int* ) ); + for ( i = 0; i <= N; ++i ) { + C[ i ] = ( long int* )malloc( ( N + 1 ) * sizeof( long int ) ); + + for ( j = 0; j <= N; ++j ) { + C[ i ][ j ] = -1; + } + } + printf( "Cost: %li\n", CountRoutes( N, N ) ); return 0; }