2016-07-11 165 views
-1

所有可能的唯一路徑幫我尋找一切可能的路徑,從頂部到達底部最右邊的單元最左邊的單元格。查找m×n矩陣

下面是限制,

  1. 不能訪問它已經訪問過的細胞。
  2. ,應當在到達出口處即右下角大多數細胞前訪問所有細胞。

試過幾個邏輯的,但沒能獲得所有路徑。由於

回答

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; 
} 

對於確定要以不同的方式表示位置,併爲更大的「矩陣」你必須擺脫「錯路」儘快。 ,但希望這可以讓你開始某個地方。