2015-04-05 63 views
0

我试图在使用递归的迷宫中找到最小路径大小。 要做到这一点,迷宫必须经历所有可能的路径,然后不断更新“最短长度”。以递归方法查找最小int(路径大小)

我能够通过所有可能的列表并打印这些坐标和路径大小,但我无法找到最小值,因为上次找到的路径总是更新为“最短长度”。

所以,我想将所有的解决路径长度到ArrayList<Integer> list的,然后创建递归之外的独立的静态类解决方法,在这里我找到了最低,并返回它的价值,solve()方法,并继续从那里。这是做这件事的最佳方法吗?或者我可以在solve()方法中找到最短长度和相应的坐标吗?

这是递归的情况下,什么样的代码:

else { 
    for(int i = 0; i < directions.length; i++) 
    { 
    Coord nextSpot = currentSpot.addTo(directions[i]); 
    if(nextSpot.validSpot(maze)) 
     if(!newPath.contains(nextSpot)){ 

     ArrayList<Coord> solution = //The recursive call 
         solve(newPath,nextSpot,goal,maze); 

     if(solution != null){ 

      int shortestLength = 100; //arbitrary large length 
     // lengths.add(lengthSolution); ?? Possible alternative? 
      System.out.println(lengthSolution); 
      System.out.println(solution); 
      if(solution.size() < shortestLength){ 
      shortestLength = solution.size(); 
      System.out.println(shortestLength); 
      } 
     } 
    }//ifs 
    }//for 
    return null; 
}//else (recursive case) 
+5

这有什么错* Dijstra算法*? – 2015-04-05 19:41:12

+0

@CommuSoft我看了那个教程,但我不确定我真的明白我将如何编写代码。这是否是这种情况的最佳方式? – kris 2015-04-05 19:43:28

+0

@ kat-如果你在实施Dijkstra的算法时遇到问题,也许一旦你从教程中练习。 'Commusoft'写的是他对解决这个问题的看法。它必须是'Dijkstra的算法'! – 2015-04-05 19:46:33

回答

0
int globalsteps =0; 

int maze(x,y,steps) { 
    if(icangoup){ maze(x+1,y,steps +1);} 
    if(icangodown){ maze(x-1,y,steps +1);} 
    if(icangoleft){ maze(x,y+1,steps +1);} 
    if(icangoright){ maze(x,y-1,steps +1);} 
    if(ifoundtheexit!!!!) { 
     if(globalsteps == 0 || steps < globalsteps) 
      globalsteps = steps; 
     } 
    } 
}