1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| import java.util.Scanner; public class Main { static int length,wideth; static int x,y; static String[][] arr; static int n; private static Scanner in; public static void main(String[] args){ in = new Scanner (System.in); System.out.println("输入迷宫的长度、宽度(行数和列数不超过50)"); wideth =in.nextInt(); length =in.nextInt(); arr = new String[wideth][length]; System.out.println("请输入"+wideth+"行"+length+"列的迷宫 ('0'表示墙,'1' 表示道路 '4'表示起点 '5'表示终点 )");
for (int i=0;i<wideth;i++) { for(int j=0;j<length;j++) { arr[i][j] = in.next(); } }
for (int i=0;i<wideth;i++) { for(int j=0;j<length;j++) { if (arr[i][j].equals("4")) { x=i; y=j; } } }
try { Running(x,y,n); }catch (Exception e) {
System.out.println(); System.out.println("找到出口!路径如下(*代表路径):"); for (int i=0;i<wideth;i++) { for(int j=0;j<length;j++) { System.out.print(arr[i][j]); if(j==length-1) System.out.println(); else System.out.print(" "); } } System.exit(0); }
System.out.println("该迷宫没有出口!!!"); }
public static void Running(int x,int y,int n){
if(arr[x][y].equals("5")||n==10000){ int i = 1/0; } if(!arr[x][y].equals("4")) arr[x][y]="*";
if(y-1>=0&&arr[x][y-1].equals("5")){ Running(x,y-1,n+1); } if(x-1>=0&&arr[x-1][y].equals("5")){ Running(x-1,y,n+1); } if(y+1<length&&arr[x][y+1].equals("5")){ Running(x,y+1,n+1); } if(x+1<wideth&&arr[x+1][y].equals("5")){ Running(x+1,y,n+1); } if(x+1<wideth&&arr[x+1][y].equals("1")){ Running(x+1,y,n+1); } if(y+1<length&&arr[x][y+1].equals("1")){ Running(x,y+1,n+1); } if(y-1>=0&&(arr[x][y-1].equals("1"))){ Running(x,y-1,n+1); } if(x-1>=0&&arr[x-1][y].equals("1")){ Running(x-1,y,n+1); }
arr[x][y]="#";
if(y-1>=0&&(arr[x][y-1].equals("*"))){ Running(x,y-1,n+1); } if(x-1>=0&&arr[x-1][y].equals("*")){ Running(x-1,y,n+1); } if(y+1<length&&arr[x][y+1].equals("*")){ Running(x,y+1,n+1); } if(x+1<wideth&&arr[x+1][y].equals("*")){ Running(x+1,y,n+1); }
} }
|