2017年大三下-人工智能-Matlab-八数码问题

1.Up函数

function B=up8(A,M)
[i,j]=find(A==0);
if(i==1)
B=-1;
return ;
end;
temp=A(i,j);
A(i,j)=A(i-1,j);
A(i-1,j)=temp;
S=A;
if(h1(M.S,S)==0)
B=-1;
return;
end;
B=S;

2.Down函数

function B=down8(A,M)
[i,j]=find(A==0);
if(j==3)
B=-1;
return ;
end;
temp=A(i,j);
A(i,j)=A(i,j+1);
A(i,j+1)=temp;
S=A;
if(h1(M.S,S)==0)
B=-1;
return;
end;
B=S;

 

3.Left函数

function B=left8(A,M)
[i,j]=find(A==0);
if(j==1)
B=-1;
return ;
end;
temp=A(i,j);
A(i,j)=A(i,j-1);
A(i,j-1)=temp;
S=A;
if(h1(M.S,S)==0)
B=-1;
return;
end;
B=S;

 

4.Right函数

function B=right8(A,M)
[i,j]=find(A==0);
if(i==3)
B=-1;
return ;
end;
temp=A(i,j);
A(i,j)=A(i+1,j);
A(i+1,j)=temp;
S=A;
if(h1(M.S,S)==0)
B=-1;
return;
end;
B=S;

 

5.H函数

function val=h1(A,T)
B=A-T;
index=find(B~=0);
val=length(index);

 

6.Output函数

function output(a)
global close8;
if(close8{a}.fa==0)
disp(close8{a}.S);
return;
end;
output(close8{a}.fa);
disp(close8{a}.S);

 

7.Main函数

function main
global min;
global open8;
global close8;
A=[2,3,0;1,5,6;8,7,4];
T=[1,2,3;8,0,4;7,6,5];
open8=cell(1);
open8{1}.g=0;
open8{1}.h=h1(A,T);
open8{1}.f=open8{1}.g+open8{1}.h;
open8{1}.S=A;
open8{1}.fa=0;
close8=cell(0);
M=open8{1};
min=1;
while(h1(A,T)~=0)
	close8{length(close8)+1}=M;
    if(M.fa~=0)
        M=close8{M.fa};
    end;
	B=up8(A,M);
	C=down8(A,M);
	D=left8(A,M);
	E=right8(A,M);
	if(B~=-1)
	 open(B,T);
	end;
	if(C~=-1)
	 open(C,T);
	end;
	if(D~=-1)
	 open(D,T);
	end;
	if(E~=-1)
	 open(E,T);
	end;
    min=1;
	for i=2:length(open8)
		if(open8{min}.f>open8{i}.f)
			min=i;
		end;
	end;
	A=open8{min}.S;
	M=open8{min};
end;
output(length(close8));
disp(A);


 

你可能感兴趣的:(2017年大三下-人工智能-Matlab-八数码问题)