recursion - Find all possible unique path in mXn matrix -
help me in finding possible path reach bottom right cell top left cell in mxn matrix.
below restrictions,
- can not visit cell visited.
- should visit cell before reaching exit i.e. bottom right cell.
tried few logic's not able paths. thanks
the simplest idea recursively try every possible non-self-crossing path, , every time such path hits bottom-right corner check whether it's length equals number of cells.
here comes naive [and slow , memory-consuming] implementation in js (judging profile know js), point algorithm in formal, unequivocal way. you're interested in "ok, let's this!" part, before helpers make example executable:
function paths(m,n) { // 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; }; // positions present in poss1 , 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; }; // can go [x,y] ? var all_next_positions = function([x,y]) { var poss = []; // assuming no diagonal moves 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 this! ////////////////////////////////// var pending = [ [[0,0]] ]; // pending partial paths (looks owl statring @ you, doesn't it?) var results = []; // corect paths found 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) { /// reaached goal, did visit cells? if(current.length == m*n) /// yes did, 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 reference evil. candidate.unshift(next_poss[i]); pending.unshift(candidate); } } } return results; }
for sure want represent positions differently, , larger "matrices" you'd have rid of "wrong paths" asap., hope gets started somewhere.
Comments
Post a Comment