帮助我找到所有可能的路径,从mXn矩阵的左上角最左边的单元格到达最右下角的单元格。
以下是限制,
尝试了一些逻辑,但无法获得所有路径。感谢
答案 0 :(得分:0)
最简单的想法是递归尝试每个可能的非自交路径,并且每次这样的路径到达右下角时检查它的长度是否等于所有单元格的数量。
这里有一个非常幼稚的[因此很慢且耗费内存的] js中的实现(根据你知道的js判断),只是为了以正式,明确的方式指出算法。你对“好吧,让我们这样做!”感兴趣部分,之前只有一些助手使这个例子实际上是可执行的:
function paths(M,N) {
// is given pos present in list of poss?
var pos_member = function(pos,poss) {
for(var i=0;i<poss.length;i++)
if(pos[0]==poss[i][0] && pos[1]==poss[i][1])
return true;
return false;
};
// all positions present in poss1 and not in poss2:
var positions_diff = function(poss1,poss2) {
var poss_d = [];
for(var i=0;i<poss1.length;i++)
if(pos_member(poss1[i],poss2)==false)
poss_d.unshift(poss1[i]);
return poss_d;
};
// where can you go from [x,y] ?
var all_next_positions = function([x,y]) {
var poss = [];
// assuming no diagonal moves are allowed;
// otherwise add 4 more next possible positions.
if(x > 0) poss.unshift([x-1,y]);
if(x < M-1) poss.unshift([x+1,y]);
if(y > 0) poss.unshift([x,y-1]);
if(y < N-1) poss.unshift([x,y+1]);
return poss;
};
//////// OK, let's do this! //////////////////////////////////
var pending = [ [[0,0]] ]; // pending partial paths (looks like an owl statring at you, doesn't it?)
var results = []; // corect paths found so far
while(pending.length>0) {
var current = pending.shift();
var last_pos = current[0];
if(last_pos[0]==M-1 && last_pos[1]==N-1) {
/// it reaached the goal, but did it visit all the cells?
if(current.length == M*N) /// yes it did, so keep it.
results.unshift(current);
} else {
/// keep going...
var next_poss = positions_diff(all_next_positions(last_pos), current);
for(var i=0;i<next_poss.length;i++) {
var candidate = current.slice(0); /// clone, because call by reference is evil.
candidate.unshift(next_poss[i]);
pending.unshift(candidate);
}
}
}
return results;
}
肯定你想要以不同的方式表示位置,对于较大的“矩阵”,你必须尽快摆脱“错误的路径”,但希望这能让你在某个地方开始。