java – 在迷宫中修改过的老鼠

前端之家收集整理的这篇文章主要介绍了java – 在迷宫中修改过的老鼠前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在接受采访时我问过你.你给我的矩阵填充了“1”和“0”.“1”表示你可以使用单元格,“0”表示单元格被阻挡.你可以向4个方向移动左,右,上,下每次你向上或向下移动它都会花费你1美元.向左或向右移动不会增加成本.所以你必须编写一个代码来检查是否可以达到目的地索引( x,y)从(0,0)开始.如果是,则打印最低成本,否则打印“-1”.

我无法计算成本.
这是我的代码

  1. public class Test {
  2. /**
  3. * @param args the command line arguments
  4. */
  5. static int dest_x = 0;
  6. static int dest_y = 0;
  7. static int cost = 0;
  8. static int m = 0;
  9. static int n = 0;
  10. public static void main(String[] args) {
  11. // TODO code application logic here
  12. Scanner in = new Scanner(System.in);
  13. Test rat = new Test();
  14. int maze[][] = {
  15. {1,1,1},{1,0},{0,1}
  16. };
  17. dest_x = in.nextInt();
  18. dest_y = in.nextInt();
  19. m = in.nextInt();
  20. n = in.nextInt();
  21. if (rat.solveMaze(maze))
  22. System.out.println("YES");
  23. else {
  24. System.out.println("NO");
  25. }
  26. System.out.println("cost = " + cost);
  27. }
  28. boolean isSafe(int maze[][],int x,int y) {
  29. // if (x,y outside maze) return false
  30. return (x >= 0 && x < m && y >= 0 &&
  31. y < n && maze[x][y] == 1);
  32. }
  33. boolean solveMaze(int maze[][]) {
  34. int sol[][] = {{0,0}
  35. };
  36. if (!solveMazeUtil(maze,sol)) {
  37. return false;
  38. }
  39. return true;
  40. }
  41. boolean solveMazeUtil(int maze[][],int y,int sol[][]) {
  42. // if (x,y is goal) return true
  43. if (x <= dest_x || y <= dest_y)
  44. if (x == dest_x && y == dest_y) {
  45. sol[x][y] = 1;
  46. return true;
  47. } else if (sol[x][y] == 1) {
  48. return false;
  49. }
  50. // Check if maze[x][y] is valid
  51. else if (isSafe(maze,x,y)) {
  52. // mark x,y as part of solution path
  53. sol[x][y] = 1;
  54. // Move forward in x direction
  55. if (solveMazeUtil(maze,x + 1,y,sol)) {
  56. //System.out.println("here at x+1 x = " + x + " y = " + y);
  57. return true;
  58. }
  59. // Move down in y direction
  60. if (solveMazeUtil(maze,y + 1,sol)) {
  61. //System.out.println("here at y+1 x = " + x + " y = " + y);
  62. cost++;
  63. return true;
  64. }
  65. cost--;
  66. if (solveMazeUtil(maze,x - 1,sol)) {
  67. // System.out.println("here at x-1 x = " + x + " y = " + y);
  68. return true;
  69. }
  70. if (solveMazeUtil(maze,y - 1,sol)) {
  71. //System.out.println("here at y-1 x = " + x + " y = " + y);
  72. cost++;
  73. return true;
  74. }
  75. cost--;
  76. /* If no solution then
  77. BACKTRACK: unmark x,y as part of solution
  78. path */
  79. sol[x][y] = 0;
  80. return false;
  81. }
  82. return false;
  83. }
  84. }
最佳答案
将迷宫变成定向图并解决最短路径问题

>标记为“1”的单元格是节点(应标记为“0”)
>如果我们可以从一个单元(节点)移动到另一个单元(节点),请使用有向边连接它们;将成本(0或1)放在边缘(请注意,我们有一个多图:两个节点可以连接两个不同的边).
>最后,在Dijkstra’s algorithm的帮助下,找到所需节点之间的最短路径(即最小成本).

猜你在找的Java相关文章