package com.java.struture; public class Mouse { private int startx, starty; private int endx,endy; private boolean success;//找到路径 public void setStart(int startx,int starty){ this.startx = startx; this.starty = starty; } public void setEnd(int endx,int endy){ this.endx = endx; this.endy = endy; } private boolean findPath(int[][]map){ return visit(map, startx, starty); } private boolean visit(int[][]map, int i, int j){ map[i][j] = 1;//老鼠走过的路径记录为1 if(i==endx && j==endy) success = true; //在二维数组阵列中依序测试四个方向,直到走到出口为止 if(!success && map[i][j+1] == 0)//0表示可以通过 visit(map, i, j+1); if(!success && map[i][j-1] == 0) visit(map, i, j-1); if(!success && map[i-1][j] == 0) visit(map, i-1 ,j); if(!success && map[i+1][j] == 0) visit(map, i+1 ,j); if(!success)//注意:失败的路径必须重置 map[i][j] = 0; return success; } public static void main(String[] args) { //2表示围墙不能通过,0表示可以通过 int [][]map = {{2, 2, 2, 2, 2, 2, 2}, {2, 0, 0, 0, 0, 0, 2}, {2, 0, 2, 0, 2, 0, 2}, {2, 0, 0, 2, 0, 2, 2}, {2, 2, 0, 2, 0, 2, 2}, {2, 0, 0, 0, 0, 0, 2}, {2, 2, 2, 2, 2, 2, 2}}; System.out.println("显示迷宫:"); for(int i = 0; i < map.length; i++) { for(int j = 0; j < map[0].length; j++) if(map[i][j] == 2) System.out.print("■"); else System.out.print(" "); System.out.println(); } Mouse mouse = new Mouse(); mouse.setStart(1, 1); mouse.setEnd(5, 5); if(!mouse.findPath(map)){ System.out.println("\n找不到出口!"); }else{ System.out.println("\n找到出口!出口为:"); for(int i = 0; i < map.length; i++) { for(int j = 0; j < map[0].length; j++) if(map[i][j] == 2) System.out.print("■"); else if(map[i][j] == 1) System.out.print("*"); else System.out.print(" "); System.out.println(); } } } }