弗雷歇算法实现


// Calculator.h: interface for the CCalculator class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_CALCULATOR_H__6CA8CEA4_E76A_446A_8E9C_B79E7788349F__INCLUDED_)
#define AFX_CALCULATOR_H__6CA8CEA4_E76A_446A_8E9C_B79E7788349F__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

typedef struct _sPoint
{
	float x;
	float y;
}sPoint;	

class CCalculator  
{
public:
	CCalculator();
	virtual ~CCalculator();
	
public:
	float CalcDistance(sPoint* p1, int p, sPoint* p2, int q);

private:
	float Cal(float** ca, int i, int j);
	float dis(int i, int j);
	float min3(float f1, float f2, float f3);
public:
	sPoint* p1;
	sPoint* p2;
	int p;
	int q;
};

#endif // !defined(AFX_CALCULATOR_H__6CA8CEA4_E76A_446A_8E9C_B79E7788349F__INCLUDED_)

弗雷歇算法实现_第1张图片

// Calculator.cpp: implementation of the CCalculator class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CalcDistance.h"
#include "Calculator.h"
#include 

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CCalculator::CCalculator()
{
	p1 = NULL;
	p2 = NULL;
	p  = 0;
	q  = 0;
}

CCalculator::~CCalculator()
{

}

float CCalculator::CalcDistance(sPoint* p1, int p, sPoint* p2, int q)
{
	float fval = 0.0;
	this->p1 = p1;
	this->p2 = p2;
	this->p  = p;
	this->q  = q;

	// init ca[p][q]
	float **ca = new float*[p];
	for(int i = 0 ; i < p ; i++)
	{
		ca[i] = new float[q];
	}
	
	for(i = 0 ; i < p ; i++)
	{
		for(int j = 0 ; j < q ; j++)
		{
			ca[i][j] = -1.0;
		}
	}

	// calc distance
	fval = Cal(ca,p-1,q-1);


	for(i = 0 ; i < p ; i++)
		delete []ca[i];
	delete []ca;

	return fval;
}

float CCalculator::Cal(float** ca, int i, int j)
{
	if(ca[i][j] > -1.0)
	{
		return ca[i][j];
	}
	else if(i == 0 && j == 0)
	{
		ca[i][j] = dis(0,0);
	}
	else if(i > 0 && j == 0)
	{
		ca[i][j] = max(Cal(ca,i-1,0),dis(i,0));
	}
	else if(i == 0 && j > 0)
	{
		ca[i][j] = max(Cal(ca,0,j-1),dis(0,j));
	}
	else if(i > 0 && j > 0)
	{
		ca[i][j] = max(min3( Cal(ca,i-1,j), Cal(ca,i-1,j-1), Cal(ca,i,j-1) ), dis(i,j));
	}
	else
	{
		ca[i][j] = 0xFFFFFFFF;
	}

	return ca[i][j];
}

float CCalculator::dis(int i, int j)
{
	return sqrt(pow(p1[i].x-p2[j].x,2) + pow(p1[i].y-p2[j].y,2));
}

float CCalculator::min3(float f1, float f2, float f3)
{
	float minf = (f1 < f2)? f1 : f2;
	minf = (minf < f3)? minf : f3;
	return minf;
}


你可能感兴趣的:(弗雷歇算法实现)