您的位置:首页 > 其它

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!还没有理解为什么。

我的代码如下:

// 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: