从矩阵的一个点移动到零的位置。

huangapple go评论109阅读模式
英文:

moving from one point of the matrix to the location of zero

问题

以下是您提供的代码的翻译部分:

  1. package rcs;
  2. import java.util.Scanner;
  3. public class A2Rcs {
  4. public static void main(String args[]) {
  5. Scanner input = new Scanner(System.in);
  6. System.out.println("请输入棋盘大小:");
  7. int size = input.nextInt();
  8. int[][] board = new int[size][size];
  9. for (int i = 0; i < size; i++) {
  10. System.out.println("请输入第 " + (i + 1) + " 行:");
  11. for (int j = 0; j < size; j++) {
  12. board[i][j] = input.nextInt();
  13. }
  14. }
  15. System.out.println("\n您输入的数据:");
  16. for (int x = 0; x < size; x++) {
  17. for (int y = 0; y < size; y++) {
  18. System.out.print(board[x][y]);
  19. }
  20. System.out.println();
  21. }
  22. System.out.println("请输入起始位置:");
  23. int p1 = input.nextInt();
  24. int p2 = input.nextInt();
  25. if (magicBoard(p1, p2, board, size))
  26. System.out.println("可解");
  27. }
  28. public static Boolean magicBoard(int p1, int p2, int[][] board, int size) {
  29. boolean result = false;
  30. int temp;
  31. while (!result) {
  32. if (board[p1][p2] == 0) {
  33. System.out.println("达到 0。");
  34. result = true;
  35. break;
  36. }
  37. // ... (接下来的代码被省略)
  38. // ... (根据您提供的信息,这部分代码存在错误,但在这里无法提供详细的错误修正)
  39. // ... (请您自行检查代码中的逻辑和错误,或提供更多细节以获得帮助)
  40. }
  41. return result;
  42. }
  43. }

注意:上述代码中的逻辑存在错误,我只翻译了您提供的部分,但无法为您修复逻辑错误。如果您需要修复代码逻辑错误,请提供更多信息,或者尝试自行调试。

英文:

I am supposed to program this with both recursive and iterative. My recursive code is posted at the bottom.
MagicBoard is a 1-player game using a chess-like board consisting of d×d squares with d between 5
and 20, and each square contains an integer between 0 and d -1. The rules of the game are simple.
The circle marks the start position on the board. The integer (n) in the circled square indicates that
the circle can move n squares on the board. In one step the circle can move either n squares east or
west or north or south. At each step the chosen direction is fixed. The circle cannot move off the
board. The only legal start positions are the four corner squares. The board must contain exactly one
goal square with zero as value that can be located anywhere on the board, but its position cannot be
identical to the start position.
从矩阵的一个点移动到零的位置。
For instance, in the above example the circle can move either 4 squares east or south. All other
moves are illegal. The objective of the game is to move the circle to the goal square containing the
zero value. In the configuration given below, you can solve the game by making the following
sequence of steps:
从矩阵的一个点移动到零的位置。

The next example shows that in some situations, the goal square cannot be reached from the given start position
从矩阵的一个点移动到零的位置。

Here is my code which does not work:

  1. import java.util.Scanner;
  2. public class A2Rcs {
  3. public static void main(String args[]) {
  4. Scanner input = new Scanner(System.in);
  5. System.out.println(&quot;\nEnter board size: &quot;);
  6. int size = input.nextInt();
  7. int[][]board = new int[size][size];
  8. for (int i = 0; i&lt;size; i++) {
  9. System.out.println(&quot;\nEnter the row: &quot;);
  10. for (int j = 0; j&lt;size; j++) {
  11. board[i][j] = input.nextInt();
  12. }
  13. }
  14. System.out.println(&quot;\nData you entered: &quot;);
  15. for(int x = 0; x&lt; size; x++){
  16. for(int y = 0 ; y&lt; size; y++){
  17. System.out.print(board[x][y]);
  18. }
  19. System.out.println();
  20. }
  21. System.out.println(&quot;\nEnter starting position: &quot;);
  22. int p1 = input.nextInt();
  23. int p2 = input.nextInt();
  24. if (magicBoard(p1, p2, board, size))
  25. System.out.println(&quot;Solvable&quot;);
  26. }
  27. public static Boolean magicBoard(int p1, int p2, int[][] board, int size) {
  28. boolean result = false;
  29. int temp;
  30. while(!result) {
  31. if(board[p1][p2] == 0) {
  32. System.out.println(&quot;Reached 0.&quot;);
  33. result = true;
  34. break;
  35. }
  36. //can only down
  37. if((p1+board[p1][p2]) &lt; size &amp;&amp; (p1-board[p1][p2]) &lt; 0 &amp;&amp; ((p2+board[p1][p2]) &gt; size &amp;&amp; (p2-board[p1][p2]) &lt; 0)) {
  38. temp = board[p1+board[p1][p2]][p2];
  39. if(board[p1][p2] == temp) {
  40. System.out.print(&quot;The MagicBoard is unsolvable&quot;);
  41. result = false;
  42. break;
  43. }
  44. // If don&#39;t go back and forth, then we continue
  45. else {
  46. p1 = p1+board[p1][p2];
  47. System.out.print(&quot;Move south &quot; + board[p1][p2] + &quot;, &quot;);
  48. magicBoard(p1, p2, board, size);
  49. }
  50. }
  51. //can only up
  52. else if((p1+board[p1][p2]) &gt; size &amp;&amp; (p1-board[p1][p2]) &gt; 0 &amp;&amp; ((p2+board[p1][p2]) &gt; size &amp;&amp; (p2-board[p1][p2]) &lt; 0)){
  53. temp = board[p1-board[p1][p2]][p2];
  54. if(board[p1][p2] == temp) {
  55. System.out.print(&quot;The MagicBoard is unsolvable&quot;);
  56. result = false;
  57. break;
  58. }
  59. else {
  60. p1 = p1-board[p1][p2];
  61. System.out.print(&quot;Move north &quot; + board[p1][p2] + &quot;, &quot;);
  62. magicBoard(p1, p2, board, size);
  63. }
  64. }
  65. //can only up right
  66. else if((p2+board[p1][p2])&lt;size &amp;&amp; (p2-board[p1][p2])&lt;0 &amp;&amp; ((p1+board[p1][p2])&gt;size &amp;&amp; (p1-board[p1][p2])&lt;0)) {
  67. temp = board[p1][p2+board[p1][p2]];
  68. if(board[p1][p2] == temp) {
  69. System.out.print(&quot;The MagicBoard is unsolvable&quot;);
  70. result = false;
  71. break;
  72. }
  73. else {
  74. p2 = p2+board[p1][p2];
  75. System.out.print(&quot;Move east &quot; + board[p1][p2] + &quot;, &quot;);
  76. magicBoard(p1, p2, board, size);
  77. }
  78. }
  79. //can only left
  80. else if((p2+board[p1][p2]) &gt; size &amp;&amp; (p2-board[p1][p2])&gt; 0 &amp;&amp; ((p1+board[p1][p2])&gt;size &amp;&amp; (p1-board[p1][p2])&lt;0)) {
  81. temp = board[p1][p2-board[p1][p2]];
  82. if(board[p1][p2] == temp) {
  83. System.out.print(&quot;The MagicBoard is unsolvable&quot;);
  84. result = false;
  85. break;
  86. }
  87. else {
  88. p2 = p2-board[p1][p2];
  89. System.out.print(&quot;Move west &quot; + board[p1][p2] + &quot;, &quot;);
  90. magicBoard(p1, p2, board, size);
  91. }
  92. }
  93. // can any direction
  94. else {
  95. // try moving south
  96. SOUTH:
  97. if(p1-board[p1][p2] &lt; 0 &amp;&amp; p1-board[p1][p2] &gt; -size) {
  98. temp = board[p1+board[p1][p2]][p2];
  99. // Verify if we go back and forth if we go south, if we do, then we the result will be
  100. if(board[p1][p2] == temp) {
  101. break SOUTH;
  102. }
  103. else {
  104. p1 = p1+board[p1][p2];
  105. System.out.print(&quot;Move south &quot; + board[p1][p2] + &quot;, &quot;);
  106. magicBoard(p1, p2, board, size);
  107. }
  108. }
  109. NORTH:
  110. if(p1-board[p1][p2] &gt; 0 &amp;&amp; p1-board[p1][p2] &lt; size) {
  111. temp = board[p1-board[p1][p2]][p2];
  112. if(board[p1][p2] == temp) {
  113. break NORTH;
  114. }
  115. else {
  116. p1 = p1-board[p1][p2];
  117. System.out.print(&quot;Move north &quot; + board[p1][p2] + &quot;, &quot;);
  118. magicBoard(p1, p2, board, size);
  119. }
  120. }
  121. // try moving east
  122. EAST:
  123. if(p2-board[p1][p2] &lt; 0 ) {
  124. temp = board[p1][p2+board[p1][p2]];
  125. // If will go back and forth at that position, then we exit the EAST label and we go to the next label
  126. if(board[p1][p2] == temp) {
  127. System.out.print(&quot;The MagicBoard is unsolvable&quot;);
  128. break EAST;
  129. }
  130. else {
  131. p2 = p2+board[p1][p2];
  132. System.out.print(&quot;Move east &quot; + board[p1][p2] + &quot;, &quot;);
  133. magicBoard(p1, p2, board, size);
  134. }
  135. }
  136. // Try moving west
  137. WEST:
  138. if(p2-board[p1][p2] &gt; 0) {
  139. temp = board[p1][p2-board[p1][p2]];
  140. // If we go back and forth in that position, then we exit the EAST label
  141. if(board[p1][p2] == temp) {
  142. System.out.print(&quot;The MagicBoard is unsolvable&quot;);
  143. result = false;
  144. break WEST;
  145. }
  146. else {
  147. p2 = p2-board[p1][p2];
  148. System.out.print(&quot;Move west &quot; + board[p1][p2] + &quot;, &quot;);
  149. magicBoard(p1, p2, board, size);
  150. }
  151. }
  152. }
  153. }
  154. return result;
  155. }
  156. }

I've been working on this for a week and still cannot figure it out. I am not sure if it is proper to post it here but any type of assistance is appreciated

edit Errors are here:
从矩阵的一个点移动到零的位置。

答案1

得分: 2

  1. function backtrack(M, i, j, visited){
  2. // Reached the goal!
  3. if (M[i][j] == 0)
  4. return [[i,j]];
  5. const d = M.length;
  6. const move = M[i][j];
  7. // Try visiting all directions
  8. if (i + move < d && !visited[i + move][j]){
  9. visited[i + move][j] = true;
  10. const ms = backtrack(M, i + move, j, visited)
  11. if (ms.length)
  12. return [[i,j]].concat(ms);
  13. visited[i + move][j] = false;
  14. }
  15. if (i - move >= 0 && !visited[i - move][j]){
  16. visited[i - move][j] = true;
  17. const ms = backtrack(M, i - move, j, visited)
  18. if (ms.length)
  19. return [[i,j]].concat(ms);
  20. visited[i - move][j] = false;
  21. }
  22. if (j + move < d && !visited[i][j + move]){
  23. visited[i][j + move] = true;
  24. const ms = backtrack(M, i, j + move, visited)
  25. if (ms.length)
  26. return [[i,j]].concat(ms);
  27. visited[i][j + move] = false;
  28. }
  29. if (j - move >= 0 && !visited[i][j - move]){
  30. visited[i][j - move] = true;
  31. const ms = backtrack(M, i, j - move, visited)
  32. if (ms.length)
  33. return [[i,j]].concat(ms);
  34. visited[i][j - move] = false;
  35. }
  36. return [];
  37. }
  38. function f(M, start_i, start_j){
  39. const d = M.length;
  40. const visited = new Array(d);
  41. for (let i=0; i<d; i++)
  42. visited[i] = new Array(d).fill(false);
  43. visited[start_i][start_j] = true;
  44. return backtrack(M, start_i, start_j, visited);
  45. }
  46. var board_1 = [
  47. [4, 2, 1, 3, 1],
  48. [2, 3, 2, 1, 4],
  49. [3, 2, 3, 1, 4],
  50. [1, 3, 4, 2, 3],
  51. [3, 3, 1, 2, 0]
  52. ];
  53. var board_2 = [
  54. [1, 4, 1, 3, 1],
  55. [4, 3, 2, 1, 4],
  56. [3, 2, 3, 1, 4],
  57. [1, 3, 4, 2, 3],
  58. [3, 4, 1, 2, 0]
  59. ];
  60. console.log(JSON.stringify(f(board_1, 0, 0)));
  61. console.log(JSON.stringify(f(board_2, 0, 0)));

1: Backtracking

英文:

We could write less code, which would make it easier to think about and consider its logic. First, it seems clear we don't need to visit a cell more than once. We can use a backtracking routine, marking and unmarking visited cells. I'm not versed in Java so I hope this JavaScript code is easy to translate:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. function backtrack(M, i, j, visited){
  2. // Reached the goal!
  3. if (M[i][j] == 0)
  4. return true;
  5. const d = M.length;
  6. const move = M[i][j];
  7. // Try visiting all directions
  8. if (i + move &lt; d &amp;&amp; !visited[i + move][j]){
  9. visited[i + move][j] = true;
  10. if (backtrack(M, i + move, j, visited))
  11. return true;
  12. visited[i + move][j] = false;
  13. }
  14. if (i - move &gt;= 0 &amp;&amp; !visited[i - move][j]){
  15. visited[i - move][j] = true;
  16. if (backtrack(M, i - move, j, visited))
  17. return true;
  18. visited[i - move][j] = false;
  19. }
  20. if (j + move &lt; d &amp;&amp; !visited[i][j + move]){
  21. visited[i][j + move] = true;
  22. if (backtrack(M, i, j + move, visited))
  23. return true;
  24. visited[i][j + move] = false;
  25. }
  26. if (j - move &gt;= 0 &amp;&amp; !visited[i][j - move]){
  27. visited[i][j - move] = true;
  28. if (backtrack(M, i, j - move, visited))
  29. return true;
  30. visited[i][j - move] = false;
  31. }
  32. return false;
  33. }
  34. function f(M, start_i, start_j){
  35. const d = M.length;
  36. const visited = new Array(d);
  37. for (let i=0; i&lt;d; i++)
  38. visited[i] = new Array(d).fill(false);
  39. visited[start_i][start_j] = true;
  40. return backtrack(M, start_i, start_j, visited);
  41. }
  42. var board_1 = [
  43. [4, 2, 1, 3, 1],
  44. [2, 3, 2, 1, 4],
  45. [3, 2, 3, 1, 4],
  46. [1, 3, 4, 2, 3],
  47. [3, 3, 1, 2, 0]
  48. ];
  49. var board_2 = [
  50. [1, 4, 1, 3, 1],
  51. [4, 3, 2, 1, 4],
  52. [3, 2, 3, 1, 4],
  53. [1, 3, 4, 2, 3],
  54. [3, 4, 1, 2, 0]
  55. ];
  56. console.log(f(board_1, 0, 0));
  57. console.log(f(board_2, 0, 0));

<!-- end snippet -->

Here's a version that also gets the moves for the first valid path found:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. function backtrack(M, i, j, visited){
  2. // Reached the goal!
  3. if (M[i][j] == 0)
  4. return [[i,j]];
  5. const d = M.length;
  6. const move = M[i][j];
  7. // Try visiting all directions
  8. if (i + move &lt; d &amp;&amp; !visited[i + move][j]){
  9. visited[i + move][j] = true;
  10. const ms = backtrack(M, i + move, j, visited)
  11. if (ms.length)
  12. return [[i,j]].concat(ms);
  13. visited[i + move][j] = false;
  14. }
  15. if (i - move &gt;= 0 &amp;&amp; !visited[i - move][j]){
  16. visited[i - move][j] = true;
  17. const ms = backtrack(M, i - move, j, visited)
  18. if (ms.length)
  19. return [[i,j]].concat(ms);
  20. visited[i - move][j] = false;
  21. }
  22. if (j + move &lt; d &amp;&amp; !visited[i][j + move]){
  23. visited[i][j + move] = true;
  24. const ms = backtrack(M, i, j + move, visited)
  25. if (ms.length)
  26. return [[i,j]].concat(ms);
  27. visited[i][j + move] = false;
  28. }
  29. if (j - move &gt;= 0 &amp;&amp; !visited[i][j - move]){
  30. visited[i][j - move] = true;
  31. const ms = backtrack(M, i, j - move, visited)
  32. if (ms.length)
  33. return [[i,j]].concat(ms);
  34. visited[i][j - move] = false;
  35. }
  36. return [];
  37. }
  38. function f(M, start_i, start_j){
  39. const d = M.length;
  40. const visited = new Array(d);
  41. for (let i=0; i&lt;d; i++)
  42. visited[i] = new Array(d).fill(false);
  43. visited[start_i][start_j] = true;
  44. return backtrack(M, start_i, start_j, visited);
  45. }
  46. var board_1 = [
  47. [4, 2, 1, 3, 1],
  48. [2, 3, 2, 1, 4],
  49. [3, 2, 3, 1, 4],
  50. [1, 3, 4, 2, 3],
  51. [3, 3, 1, 2, 0]
  52. ];
  53. var board_2 = [
  54. [1, 4, 1, 3, 1],
  55. [4, 3, 2, 1, 4],
  56. [3, 2, 3, 1, 4],
  57. [1, 3, 4, 2, 3],
  58. [3, 4, 1, 2, 0]
  59. ];
  60. console.log(JSON.stringify(f(board_1, 0, 0)));
  61. console.log(JSON.stringify(f(board_2, 0, 0)));

<!-- end snippet -->

答案2

得分: 1

  1. // 以下是一个魔术棋盘问题的广度优先搜索(BFS)解法的最小可复现示例(MRE):
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.LinkedList;
  5. import java.util.List;
  6. import java.util.Queue;
  7. public class A2Rcs {
  8. private static int[][] board1 = { // 测试案例1
  9. {4, 2, 1, 3, 1},
  10. {2, 3, 2, 1, 4},
  11. {3, 2, 3, 1, 4},
  12. {1, 3, 4, 2, 3},
  13. {3, 3, 1, 2, 0}
  14. };
  15. private static int[][] board2 = { // 测试案例2
  16. {1, 4, 1, 3, 1},
  17. {4, 3, 2, 1, 4},
  18. {3, 2, 3, 1, 4},
  19. {1, 3, 4, 2, 3},
  20. {3, 4, 1, 2, 0}
  21. };
  22. private static boolean[][] visited; // 标记已访问节点
  23. private static Queue<List<int[]>> queue; // BFS使用队列。在这种情况下,队列中的每个条目(列表)代表整个路径。此类路径由一系列行、列对表示。
  24. public static void main(String[] args) {
  25. magicBoard(0, 0, board1);
  26. magicBoard(0, 0, board2);
  27. }
  28. public static Boolean magicBoard(int row, int col, int[][] board) {
  29. List<int[]> path = new ArrayList<>(); // 构造一个空路径
  30. path.add(new int[]{row, col}); // 将起始点添加到路径中
  31. queue = new LinkedList<>(); // 初始化队列
  32. queue.add(path); // 将路径添加到队列中
  33. visited = new boolean[board.length][board[0].length]; // 初始化已访问数组
  34. for (int i = 0; i < visited.length; i++) {
  35. for (int j = 0; j < visited[0].length; j++) {
  36. visited[i][j] = false;
  37. }
  38. }
  39. visited[row][col] = true; // 将起始点标记为已访问
  40. boolean result = magicBoardBFS(board); // 运行搜索
  41. if (!result) {
  42. System.out.println("\n未找到路径。");
  43. }
  44. return result;
  45. }
  46. public static Boolean magicBoardBFS(int[][] board) {
  47. List<int[]> path = queue.poll(); // 从队列中取出头部(第一个加入的)条目
  48. if (path == null) return false; // 没有更多条目需要处理且未找到目标,因此返回false
  49. if (targetFound(board, path)) return true; // 检查是否达到目标
  50. int[] rowColumnPair = path.get(path.size() - 1); // 路径中的最后一个行、列对
  51. // 获取下一个可到达位置
  52. List<int[]> neighbors = getNeighbors(board, rowColumnPair[0], rowColumnPair[1]);
  53. // 将邻居添加到队列
  54. for (int[] rowColPair : neighbors) {
  55. List<int[]> newPath = new ArrayList<>(path); // 复制路径
  56. // 并将邻居(下一个可到达位置)添加到路径中
  57. newPath.add(rowColPair);
  58. queue.add(newPath); // 将新路径添加到队列中
  59. }
  60. return magicBoardBFS(board);
  61. }
  62. // 检查路径中的最后一对是否为目标
  63. private static boolean targetFound(int[][] board, List<int[]> path) {
  64. int[] rowColPair = path.get(path.size() - 1); // 路径中的最后一个行、列对
  65. int row = rowColPair[0], col = rowColPair[1];
  66. if (board[row][col] == 0) { // 找到目标
  67. System.out.println("找到路径:");
  68. printPath(path);
  69. return true;
  70. }
  71. return false;
  72. }
  73. private static List<int[]> getNeighbors(int[][] board, int row, int col) {
  74. List<int[]> neighbors = new ArrayList<>();
  75. int move = board[row][col];
  76. // 待办事项: 断言移动大于0
  77. int[][] newRowColPairs = {{row + move, col}, {row - move, col}, {row, col + move}, {row, col - move}};
  78. for (int[] rowColPair : newRowColPairs) {
  79. int newRow = rowColPair[0], newCol = rowColPair[1];
  80. if (newRow < board.length && newRow >= 0
  81. && newCol < board[0].length && newCol >= 0) { // 有效的行、列
  82. if (!visited[newRow][newCol]) { // 未访问过
  83. neighbors.add(new int[]{newRow, newCol});
  84. visited[newRow][newCol] = true;
  85. }
  86. }
  87. }
  88. return neighbors;
  89. }
  90. private static void printPath(List<int[]> path) {
  91. if (path == null) return;
  92. for (int[] rowColPair : path) {
  93. System.out.print(Arrays.toString(rowColPair) + " ");
  94. }
  95. System.out.println();
  96. }
  97. }

(1) 在发布问题或回答时,始终考虑MRE。

英文:

The search is a classic Breadth-first search (BFS) and can be solved by recursive BFS.<br/>
The following is an mre <sup>(1)</sup> of a BFS solution for the MagicBoard:

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import java.util.Queue;
  6. public class A2Rcs {
  7. private static int[][] board1 = {//test case 1
  8. {4, 2, 1, 3, 1},
  9. {2, 3, 2, 1, 4},
  10. {3, 2, 3, 1, 4},
  11. {1, 3, 4, 2, 3},
  12. {3, 3, 1, 2, 0}
  13. };
  14. private static int[][] board2 = {//test case 2
  15. {1, 4, 1, 3, 1},
  16. {4, 3, 2, 1, 4},
  17. {3, 2, 3, 1, 4},
  18. {1, 3, 4, 2, 3},
  19. {3, 4, 1, 2, 0}
  20. };
  21. private static boolean[][] visited; //mark visited nodes
  22. //bfs uses queue. In this case each entry (List) in the queue represents an entire path.
  23. //such path is represented by a list of row, column pairs
  24. private static Queue&lt;List&lt;int[]&gt;&gt; queue;
  25. public static void main(String[] args) {
  26. magicBoard(0, 0, board1);
  27. magicBoard(0, 0, board2);
  28. }
  29. public static Boolean magicBoard(int row, int col, int[][] board) {
  30. List&lt;int[]&gt; path = new ArrayList&lt;&gt;(); //construct an empty path
  31. path.add(new int[]{row,col}); //add starting point to the path
  32. queue = new LinkedList&lt;&gt;(); //initialize queue
  33. queue.add(path);//add path to queue
  34. visited = new boolean[board.length][board[0].length]; //initialize visited
  35. for (int i=0; i&lt;visited.length ; i++){
  36. for (int j=0; j&lt;visited[0].length ; j++){
  37. visited[i][j] = false;
  38. }
  39. }
  40. visited[row][col] = true;//mark origin as visited
  41. boolean result = magicBoardBFS(board); //run search
  42. if (! result) {
  43. System.out.println(&quot;\nPath not found.&quot;);
  44. }
  45. return result;
  46. }
  47. public static Boolean magicBoardBFS(int[][] board) {
  48. List&lt;int[]&gt;path = queue.poll(); //pull head (first entered) entry from queue
  49. if(path == null) return false; //no more entries to process and target not found so return false
  50. if(targetFound(board, path)) return true; //check if target reached
  51. int[] rowColumnPair = path.get(path.size()-1); //last row, col pair in path
  52. //get next reachable positions
  53. List&lt;int[]&gt;neighbors = getNeighbors(board, rowColumnPair[0], rowColumnPair[1]);
  54. //add neighbors to queue
  55. for(int[] rowColPair : neighbors){
  56. List&lt;int[]&gt;newPath = new ArrayList&lt;&gt;(path); //copy path
  57. //and neighbor (next reachable position) to the path
  58. newPath.add(rowColPair);
  59. queue.add(newPath); //add new path to queue
  60. }
  61. return magicBoardBFS(board);
  62. }
  63. //check if last pair in path is the target
  64. private static boolean targetFound(int[][] board,List&lt;int[]&gt;path ) {
  65. int[] rowColPair = path.get(path.size()-1); //last row, col pair in path
  66. int row = rowColPair[0], col = rowColPair[1];
  67. if(board[row][col] == 0 ){//target found
  68. System.out.println(&quot;Path found: &quot;);
  69. printPath(path);
  70. return true;
  71. }
  72. return false;
  73. }
  74. private static List&lt;int[]&gt; getNeighbors(int[][] board, int row, int col) {
  75. List&lt;int[]&gt;neighbors = new ArrayList&lt;&gt;();
  76. int move = board[row][col];
  77. //todo : assert that move is &gt; 0
  78. int[][] newRowColPairs = {{row + move, col},{row - move, col}, {row , col + move},{row , col - move} };
  79. for(int[] rowColPair: newRowColPairs){
  80. int newRow = rowColPair[0], newCol =rowColPair[1];
  81. if(newRow &lt; board.length &amp;&amp; newRow &gt;= 0
  82. &amp;&amp; newCol &lt; board[0].length &amp;&amp; newCol &gt;=0) { //valid row col
  83. if(!visited[newRow][newCol]) { //unvisited
  84. neighbors.add(new int[]{newRow, newCol});
  85. visited[newRow][newCol] = true;
  86. }
  87. }
  88. }
  89. return neighbors;
  90. }
  91. private static void printPath(List&lt;int[]&gt; path) {
  92. if(path == null) return;
  93. for(int[] rowColPair : path){
  94. System.out.print(Arrays.toString(rowColPair) +&quot; &quot;);
  95. }
  96. System.out.println();
  97. }
  98. }

<hr>
<sup>(1)</sup> Always consider mre when posting a question or an answer

huangapple
  • 本文由 发表于 2020年10月27日 06:47:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64546043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定