跳马问题的matlab代码实现

中国象棋棋盘有10行9列,我们需要计算马走到每个点的步数,并将结果储存在10*9的矩阵中,起点键入 需要具体代码

大概是这样:
函数脚本:


%y_row
%x_col
function HorseGo(y,x,ylast,xlast, n)
global BigA;
%如果在棋盘外 结束
if((x<1 ||x>9 || y<1 ||y>10))
    return;
end
    
n=n+1;

%八种跳法
xtemp = 0;
ytemp = 0;
fuzhiFlag = 0;
%左上
xtemp = x-2;
ytemp = y-1;

% (算完的坐标等于上把的位置 否则就又跳回去了) || (这么跳 新位置在棋盘外)||((此处现有值更小)&& (此处值不为0)))
if( (ylast==ytemp && xtemp==xlast)||(xtemp<1 ||xtemp>9 || ytemp<1 ||ytemp>10) || (BigA(ytemp,xtemp)<=n && BigA(ytemp,xtemp)~= 0))
    
else
    BigA(ytemp,xtemp) = n;
    fuzhiFlag=1;
end

%左下
xtemp = x-2;
ytemp = y+1;
if( (ylast==ytemp && xtemp==xlast)||(xtemp<1 ||xtemp>9 || ytemp<1 ||ytemp>10) || (BigA(ytemp,xtemp)<=n && BigA(ytemp,xtemp)~= 0))
    
else
    BigA(ytemp,xtemp) = n;
    fuzhiFlag=1;
end
%上左
xtemp = x-1;
ytemp = y-2;
if( (ylast==ytemp && xtemp==xlast)||(xtemp<1 ||xtemp>9 || ytemp<1 ||ytemp>10) || (BigA(ytemp,xtemp)<=n && BigA(ytemp,xtemp)~= 0))
    
else
    BigA(ytemp,xtemp) = n;
    fuzhiFlag=1;
end
%上右
xtemp = x+1;
ytemp = y-2;
if( (ylast==ytemp && xtemp==xlast)||(xtemp<1 ||xtemp>9 || ytemp<1 ||ytemp>10) || (BigA(ytemp,xtemp)<=n && BigA(ytemp,xtemp)~= 0))
    
else
    BigA(ytemp,xtemp) = n;
    fuzhiFlag=1;
end

%右上
xtemp = x+2;
ytemp = y-1;
if( (ylast==ytemp && xtemp==xlast)||(xtemp<1 ||xtemp>9 || ytemp<1 ||ytemp>10) || (BigA(ytemp,xtemp)<=n && BigA(ytemp,xtemp)~= 0))
    
else
    BigA(ytemp,xtemp) = n;
    fuzhiFlag=1;
end

%右下
xtemp = x+2;
ytemp = y+1;
if( (ylast==ytemp && xtemp==xlast)||(xtemp<1 ||xtemp>9 || ytemp<1 ||ytemp>10) || (BigA(ytemp,xtemp)<=n && BigA(ytemp,xtemp)~= 0))
    
else
    BigA(ytemp,xtemp) = n;
    fuzhiFlag=1;
end

%下左
xtemp = x-1;
ytemp = y+2;
if( (ylast==ytemp && xtemp==xlast)||(xtemp<1 ||xtemp>9 || ytemp<1 ||ytemp>10) || (BigA(ytemp,xtemp)<=n && BigA(ytemp,xtemp)~= 0))
    
else
    BigA(ytemp,xtemp) = n;
    fuzhiFlag=1;
end

%下右
xtemp = x+1;
ytemp = y+2;
if( (ylast==ytemp && xtemp==xlast)||(xtemp<1 ||xtemp>9 || ytemp<1 ||ytemp>10) || (BigA(ytemp,xtemp)<=n && BigA(ytemp,xtemp)~= 0))
    
else
    BigA(ytemp,xtemp) = n;
    fuzhiFlag=1;
end
    
    if(fuzhiFlag==0)
        return;
    end;
  %如果都非零
  if(all(BigA))
      return;
  else
      
%左上      
xtemp1 = x-2;
ytemp1 = y-1;
%左下
xtemp2 = x-2;
ytemp2 = y+1;
%上左
xtemp3 = x-1;
ytemp3 = y-2;
%上右
xtemp4 = x+1;
ytemp4 = y-2;
%右上
xtemp5 = x+2;
ytemp5 = y-1;
%右下
xtemp6 = x+2;
ytemp6 = y+1;
%下左
xtemp7 = x-1;
ytemp7 = y+2;
%下右
xtemp8 = x+1;
ytemp8 = y+2;

    HorseGo(ytemp1, xtemp1,y,x,n);
    HorseGo(ytemp2,xtemp2, y,x,n);
    HorseGo(ytemp3,xtemp3, y,x,n);
    HorseGo(ytemp4, xtemp4,y,x,n);
    HorseGo(ytemp5, xtemp5,y,x,n);
    HorseGo(ytemp6, xtemp6,y,x,n);
    HorseGo(ytemp7,xtemp7, y,x,n);
    HorseGo(ytemp8,xtemp8,y,x, n);
end



调用函数的脚本


%象棋 马走法
global BigA;
BigA = zeros(10,9);
% 马的初始位置
InitPos_y_row = 1;
InitPos_x_col = 2;

HorseGo(InitPos_y_row,InitPos_x_col,-9999,-999,0);
%初始位置置0
BigA(InitPos_y_row,InitPos_x_col)=0;

img