MainClass.java public class MainClass { public static void main(String args[]){ int Y= Integer.MAX_VALUE;//最优解 int N = Integer.MIN_VALUE;//无解 int maze[][] = {{0,N,0,0,0}, {0,0,0,0,N}, {N,0,N,0,0}, {0,0,0,N,Y}}; Mouse jerry = new Mouse(); jerry.walkMaze(maze,Y,N); }}
Mouse.javapublic class Mouse { int mousePI = 0; //老鼠初始位置 int mousePJ = 0; //老鼠初始位置 int rows; int columns; int maze[][]; //迷宫 int Y ;//最优解 int N ;//无解 public void walkMaze(int maze[][],int yes,int no) { this.maze = maze; Y = yes;//最优解 N = no;//无解 rows = maze.length; columns = maze[0].length; System.out.println("迷宫初始状态:"); showMaze(); //贪心算法:当前位置周围的最大的整数之一是局部最优解之一, //即老鼠选择的下一个位置。 while(maze[mousePI][mousePJ]!=Y){ //如果不是最优解 System.out.printf("老鼠达到位置(%d,%d)
",mousePI,mousePJ); maze[mousePI][mousePJ] = maze[mousePI][mousePJ]-1;//降低优先度 int m =mousePI; int n =mousePJ; int max = maze[mousePI][mousePJ]; if(mousePI<rows-1){ //以下算法:在当前位置的周围寻找最优解(最优位置): if(maze[mousePI+1][mousePJ]>max){ max = maze[mousePI+1][mousePJ]; m = mousePI+1; n = mousePJ; } } if(mousePI>=1){ if(maze[mousePI-1][mousePJ]>max){ max = maze[mousePI-1][mousePJ]; m =mousePI-1; n = mousePJ; } } if(mousePJ<columns-1){ if(maze[mousePI][mousePJ+1]>max){ max = maze[mousePI][mousePJ+1]; m = mousePI; n = mousePJ+1; } } if(mousePJ>=1){ if(maze[mousePI][mousePJ-1]>max){ max = maze[mousePI][mousePJ-1]; m = mousePI; n = mousePJ-1; } } mousePI = m; mousePJ = n; } System.out.println("
找到最优解:"+maze[mousePI][mousePJ]); System.out.printf("老鼠位置(%d,%d)
",mousePI,mousePJ); showMaze(); } void showMaze(){ //输出二维数组 for(int i=0;i<rows;i++) { for(int j=0;j<columns;j++){ if(maze[i][j]==N) System.out.printf("%6s","#");//代表墙 else if(maze[i][j]==Y) System.out.printf("%6s","*");//代表出口 else System.out.printf("%6s",""+maze[i][j]); } System.out.println(); } }}