交易利他主义者,
我正在尝试从左上角(0,0)到右下角(N-1,N-1)在NxN的二维正方形矩阵中找到最大求和路径。我可以从(i,j)点移动到(i + 1,j),(i,j + 1),(i + 1,j + 1),(i-1,j)的任意8个可能方向(i,j-1),(i-1,j-1),(i + 1,j-1)和(i-1,j + 1),如果可能的方向在矩阵尺寸范围内。矩阵的所有元素都是正的,并且元素中没有副本。
我在MATLAB中尝试了以下方法,并得到了奇怪的结果,即仅从可能的8个方向中得出了两个方向。for example click here 附言如果我可以获得到矩阵中任意点的最大求和路径,这也将有所帮助
%% Main Dynamic Programming
A=int8(100*round((rand(5,5)),2)); % Cost Matrix
dp=zeros(size(A)); % Secondary matrix for keeping track of the costwhile
% traversing
direction=[1 1;0 1;1 0;-1 -1; -1 1;1 -1;-1 0;0 -1];% 8 possible move
for i=1:length(A)
for j=1:length(A)
neighbor_points=zeros(length(direction),2);
cost=zeros(1,length(direction));
current_point=[i j];
for n=1:length(direction)
neighbor_points(n,:)=current_point+direction(n,:);
neighborX =neighbor_points(n,1);
neighborY =neighbor_points(n,2);
if(neighborX >=1 && neighborX <=size_grid && neighborY
>=1 && neighborY <=size_grid)
cost(n)=dp(neighborX, neighborY);
end
end
[~,ind]=max(cost);
dp(i,j)=A(i,j)+dp(neighbor_points(ind,1),neighbor_points(ind,2));
fprintf('dp(%d,%d) is updated to %f.\n',i,j,dp(i,j));
end
end
%% Back Tracking from end point to start point
ii=1;
end_point=[length(A) length(A)];
Traject(ii,:)=end_point;
current_point=end_point;
while ii>0
ii=ii+1;
back_track=dp(current_point(1),current_point(2))-
A(current_point(1),current_point(2));
k=find(abs(dp-back_track)<10^-6) ;
[i, j] = ind2sub(size(A),k);
new_point=[i j];
disp(back_track)
%disp(new_point)
Traject(ii,:)=new_point;
if new_point(1)==1 && new_point(2)==1
break
end
current_point=new_point;
end
Trajectory=Traject;
我是动态编程领域的新手,因此正在寻求专家的帮助。也许我的算法有问题。预先感谢