MATLAB,316个305 300 293字节
function P=f(a,b);z(a,b)=0;P=z;c=@(X)conv2(+X,[0,1,0;1,1,1;0,1,0],'s');B=1;while B;P=z;P(1)=1;for K=1:a*b;S=z;S(a,b)=1;for L=2:a*b;S(~S&c(S)&~P)=L;end;[i,j]=find(S&c(P==K));if i;r=randi(nnz(i));else;break;end;P(i(r),j(r))=K+1;if P(a,b);break;end;end;B=any(any(c(P>0)>3));end;P(P>0)=35;P=[P,'']
感谢@LuisMendo的各种建议和一堆字节=)
在线尝试!(没有保修:请注意,需要一些调整才能使其在Octave上运行:首先,我需要删除function
关键字并对值进行硬编码,其次:在Matlab中,空格无法正确打印。同样,我也没有这样做检查八度的卷积命令,这可能会有所不同。)
输入的示例输出(7,10)
(可能已经花了一段时间):
#
#
##
##
# ###
# # ##
##### #
说明
这将以所需的4连通性从左上到右下依次生成路径,然后使用拒绝采样拒绝确实违反了不能包含相邻部分的条件的路径。
function P=f(a,b);
z(a,b)=0; % a matrix of zeros of the size of th efield
P=z;
c=@(X)conv2(+X,[0,1,0;1,1,1;0,1,0],'s'); % our convolution function, we always convolute with the same 4-neighbourhood kernel
B=1;
while B; % while we reject, we generate paths:
P=z;
P(1)=1; % P is our path, we place the first seed
for K=1:a*b; % in this loop we generate the all shortest paths (flood fill) from the bottom right, withot crossing the path to see what fiels are reachable from the bottom left
S=z;
S(a,b)=1; % seed on the bottom left
for L=2:a*b;
S(~S&c(S)&~P)=L; % update flood front
end;
[i,j]=find(S&c(P==K)); % find a neighbour of the current end of the path, that is also reachable from the bottom left
if i; % if we found some choose a random one
r=randi(nnz(i));
else;
break; % otherwise restart (might not be necessary, but I'm too tired to think about it properly=)
end;
P(i(r),j(r))=K+1; % update the end of the current path
if P(a,b); % if we finished, stop continuing this path
break;
end;
end;
B=any(any(c(P>0)>3)); % check if we actually have a valid path
end;
P(P>0)=35; % format the path nicely
P=[P,''];
哦,一如既往:
卷积是成功的关键。