使用递归穿越迷宫: /** * Attempts to recursively traverse the maze. Inserts special * characters indicating locations that have been tried and that * eventually become part of the solution. * * @param row the integer value of the row * @param column the integer value of the column * @return true if the maze has been solved */ public boolean traverse (int row, int column) { boolean done = false; if (valid (row, column)) { grid[row][column] = TRIED; // this cell has been tried if (row == grid.length-1 && column == grid[0].length-1) done = true; // the maze is solved else { done = traverse (row+1, column); // down if (!done) done = traverse (row, column+1); // right if (!done) done = traverse (row-1, column); // up if (!done) done = traverse (row, column-1); // left } if (done) // this location is part of the final path grid[row][column] = PATH; } return done; } /** * Determines if a specific location is valid. * * @param row the column to be checked * @param column the column to be checked * @return true if the location is valid */ private boolean valid (int row, int column) { boolean result = false; /** check if cell is in the bounds of the matrix */ if (row >= 0 && row < grid.length && column >= 0 && column < grid[row].length) /** check if cell is not blocked and not previously tried */ if (grid[row][column] == 1) result = true; return result; } 汉诺塔: /** * Moves the specified number of disks from one tower to another * by moving a subtower of n-1 disks out of the way, moving one * disk, then moving the subtower back. Base case of 1 disk. * * @param numDisks the number of disks to move * @param start the starting tower * @param end the ending tower * @param temp the temporary tower */ private void moveTower (int numDisks, int start, int end, int temp) { if (numDisks == 1) moveOneDisk (start, end); else { moveTower (numDisks-1, start, temp, end); moveOneDisk (start, end); moveTower (numDisks-1, temp, end, start); } } /** * Prints instructions to move one disk from the specified start * tower to the specified end tower. * * @param start the starting tower * @param end the ending tower */ private void moveOneDisk (int start, int end) { System.out.println ("Move one disk from " + start + " to " + end); }