projecteuler problem 15 solution
2009-05-05 14:39
330 查看
Starting in the top left corner of a 2*2 grid, there are 6 routes (without backtracking) to the bottom right corner.
How many routes are there through a 20*20 grid?
我的思路是从左上角的顶点开始压栈,每个点弹出来后将其相邻的点的值(右边和下边两点)+1,如果这两点(也有可能只有一点,如果被处理的点位于边框上)的值为0则压栈。然后返回grid[20][20]就ok了。小心整数溢出!
更强的解法是直接用阶乘,20!还没有理解为什么。
我的代码如下:
How many routes are there through a 20*20 grid?
我的思路是从左上角的顶点开始压栈,每个点弹出来后将其相邻的点的值(右边和下边两点)+1,如果这两点(也有可能只有一点,如果被处理的点位于边框上)的值为0则压栈。然后返回grid[20][20]就ok了。小心整数溢出!
更强的解法是直接用阶乘,20!还没有理解为什么。
我的代码如下:
// Routes.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <fstream> #include <queue> using namespace std; long long grid[22][22]; class Point { public: int x; int y; Point(int x, int y):x(x),y(y) {} Point(){} }; long long count(int indexX,int indexY) { memset(grid,0,sizeof(grid)); queue<Point> q; q.push(Point(0,0)); grid[0][0] = 1; Point temp; do{ temp = q.front(); q.pop(); if(temp.x < indexX) { if(grid[temp.y][temp.x +1] == 0) { q.push(Point(temp.x + 1,temp.y)); } grid[temp.y][temp.x + 1] += grid[temp.y][temp.x]; } if(temp.y < indexY) { if(grid[temp.y + 1][temp.x ] == 0) { q.push(Point(temp.x,temp.y + 1)); } grid[temp.y + 1][temp.x] += grid[temp.y][temp.x]; } }while(!q.empty()); return grid[indexY][indexX]; } int _tmain(int argc, _TCHAR* argv[]) { //cout << count(1,1) << endl; cout << " 2 * 2 " << count(2,2) << endl; cout << count(3,3) << endl; cout << count(20,20) << endl; ofstream outf("grid.html"); outf << "<table>" << endl; for(int i = 0; i < 21; i++) { for(int j = 0; j < 21; j++) { outf << "<td>" << grid[i][j] << "</td>" << endl; } outf << "</tr>" << endl; } outf << "</table>" << endl; system("pause"); return 0; }
相关文章推荐
- project euler Problem 15
- Project Euler problem 15
- http://projecteuler.net/problem=15 [Answer:137846528820]
- Project Euler Problem 15
- Project Euler Problem 05 C# solution
- project euler Problem 15
- Project Euler Problem 15
- Project Euler Problem 15 Lattice paths
- project euler problem 15
- My Solution to Project Euler in Ruby
- Matlab 编程 Project Euler Problem 20 Factorial digit sum
- Project euler problem 31 - 40
- project euler Problem 53
- Project Euler Problem 81
- Project Euler Problem 387 - Harshad Numbers - 深度优先
- Project Euler Problem 1
- 斐波那契数列偶数项求和(Project Euler Problem 2)
- Project Euler problem 25
- Project Euler problem 36
- Project Euler problem 42