public class maze1 { /**
 * @param args
 */
private static int maze[][]={{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}};
private static int success=0;
private static int visit(int i,int j){
maze[i][j]=1;
//System.out.println();
if(i==5&&j==5){
success=1;
}
if(success!=1&&maze[i-1][j]==0){
visit(i-1,j);
}else if(success!=1&&maze[i][j-1]==0){
visit(i,j-1);
}else if(success!=1&&maze[i][j+1]==0){
visit(i,j+1);
}else if(success!=1&&maze[i+1][j]==0){
visit(i+1,j);
}
if(success!=1)
maze[i][j]=0;
return success;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
visit(1,1);
for(int i=0;i<7;i++){
for(int j=0;j<7;j++){
if(maze[i][j]==2)
System.out.print("█");
else if(maze[i][j]==1)
System.out.print("·");
else
System.out.print(" ");
}
System.out.println(" ");
}
}
}这是我写的老鼠走迷宫的源代码,貌似没有问题呀,怎么最后没有显示出预期的结果呀,帮忙看看

解决方案 »

  1.   

    /*
    小鼠走迷宫问题,2表示墙壁,1 表示走过的路径
    */
    import java.io.*;
    class MiGong{
    static int starti, startj, endi, endj;
    static boolean flag = false; public static void init() {
    int a[][] = { { 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 } };
    for (int i = 0; i < 7; i++) {
    for (int j = 0; j < 7; j++) {
    if (a[i][j] == 2) {
    System.out.print("█");
    } else {
    System.out.print("  "); }
    }
    System.out.println();
    }
    if (!judge(a, starti, startj)) {
    System.out.println("没有找到出路");
    } else {
    System.out.println("找到了出路");
    for (int i = 0; i < 7; i++) {
    for (int j = 0; j < 7; j++) { if (a[i][j] == 2)
    System.out.print("█");
    else if (a[i][j] == 0)
    System.out.print("  ");
    else
    System.out.print(a[i][j]+" ");
    }
    System.out.println();
    }
    }
    } public static boolean judge(int[][] a, int i, int j) {
    a[i][j] = 1;
    if (i == endi && j == endj)
    flag=true;
    if (!flag && a[i][j + 1] == 0)
    judge(a, i, j + 1);
    if (!flag && a[i + 1][j] == 0)
    judge(a, i + 1, j);
    if (!flag && a[i][j - 1] == 0)
    judge(a, i, j - 1);
    if (!flag && a[i - 1][j] == 0)
    judge(a, i - 1, j);
    if (!flag)
    a[i][j] = 0;
    return flag;
    } public static void main(String args[]) throws Exception {
    System.out.println("请输入出口和入口ex:(1,1)(2,2)");
    BufferedReader buf = new BufferedReader(
    new InputStreamReader(System.in));
    String s = buf.readLine();
    starti = Integer.parseInt(s.substring(1, 2));
    startj = Integer.parseInt(s.substring(3, 4));
    endi = Integer.parseInt(s.substring(6, 7));
    endj = Integer.parseInt(s.substring(8, 9));
    init();
    }
    }这是曾经我写的,你对照下思路