%calcola la distanza tra la casella (x1, y1) e la casella (x2, y2), 
%in particolare(f, g) = (x1-x2, y1-y2)

function m=caciocavallo(f, g)
B=[1 2 1 3 1 4 2 3 2 4 3 4];
K=[1 1 1 1; 1 -1 1 1; 1 1 -1 1; 1 1 1 -1; 1 -1 -1 1; 1 -1 1 -1; 1 1 -1 -1; 1 -1 -1 -1; -1 1 1 1; -1 -1 1 1; -1 1 -1 1; -1 1 1 -1; -1 -1 -1 1; -1 -1 1 -1; -1 1 -1 -1; -1 -1 -1 -1];

if(f<0)
	f=-f;
endif
if(g<0)
	g=-g;
endif
if(f<g)
	temp=f;
	f=g;
	g=temp;
endif
if([f,g] == [1,0])
	m=3;
elseif([f,g] == [1,1])
	m=2;
elseif([f,g] == [2,0])
	m=2;
else
	for i=1:16
		A=[-3*K(i,1) -4*K(i,1); -K(i,2) 0; 3*K(i,3) 5*K(i,3); -K(i,4) -3*K(i,4)];
		b=[K(i,1)*(2*g+f); 0; K(i,3)*(-2*g-f); K(i,4)*(g+f)];
		c1=brodaglia(f, g, K(i,:));
		c=[c1(1) c1(2)];
		d=c1(3);
	
		n=length(B)/2;
		Z=zeros(0,1);
		for j=1:2:n
			b1=[b(B(j)); b(B(j+1))];
			A1=[A(B(j),:); A(B(j+1),:)];
			Z1=inv(A1)*b1;
			Z=[Z; Z1];
		endfor
	
	
	
		X=zeros(0,1);
		for k=1:2:n
			X=[X;Z(k)];
		endfor
		%printf("ascisse dei vertici del dominio in R^2\n");
		%X
	
		Y=zeros(0,1);
		for h=1:2:n
			Y=[Y;Z(h+1)];
		endfor
		%printf("ordinate dei vertici del dominio in R^2\n");
		%Y
		
		if(min(X)-fix(min(X))>0)
			xMin=fix(min(X))+1;
		else
			xMin=fix(min(X));
		endif
	
		if(min(Y)-fix(min(Y))>0)
			yMin=fix(min(Y))+1;
		else
			yMin=fix(min(Y));
		endif
	
		if(max(X)-fix(max(X))>=0)
			xMax=fix(max(X));
		else
			xMax=fix(max(X))-1;
		endif
	
		if(max(Y)-fix(max(Y))>=0)
			yMax=fix(max(Y));
		else
			yMax=fix(max(Y))-1;
		endif
		%xMin
		%xMax
		%yMin
		%yMax
		if(xMax-xMin>=1 && yMax-yMin>=1)
			Y=zeros(2,0);
			for ii=xMin:xMax
				for jj=yMin:yMax
					if (A*[ii; jj]<=b) == [1; 1; 1; 1]			
						Y=[Y [ii; jj]];
					endif
				endfor
			endfor
			if(size(Y)==[2, 0])
				m(i)=99999;
			else
				%printf("punti del dominio in Z*Z\n");
				%Y
	
				Y=c*Y;
				%printf("distanza momentanea\n");
				m(i)=d+min(Y);
			endif
		else
			m(i)=99999;
		endif
	endfor
	m=min(m);
endif