说起递归算法有点难度的。正在学习中。今天在书上学了求解迷宫的算法。算是对递归的认识又增进了一步。

一下是算法:

package hagar;

import java.util.*;

public class g1 {

public static int maze[][]={

{1,1,1,1,1,1,1},

{1,0,1,0,0,0,1},

{1,1,0,1,1,0,1},

{1,1,0,1,1,0,1},

{1,1,1,0,1,1,1},

{1,0,0,1,0,1,1},

{1,1,1,1,0,0,1},

{1,1,1,1,1,1,1}

};

public static void main(String[]args)

{

int i,j;

System.out.println("the maze:");

System.out.println("the source is(1,1),the destination is(6,5)");

way(1,1);

System.out.println("the way is:");

for(i=0;i<8;i++)

{

for(j=0;j<7;j++)

System.out.print(maze[i][j]+" ");

System.out.println("");

}

}

public static boolean way(int x,int y)

{

if(maze[6][5]==2)

return true;//end

else if(maze[x][y]==0)

{

maze[x][y]=2;

if(way(x,y-1))//up

return true;

else if(way(x+1,y-1))//right up

return true;

else if(way(x+1,y))//right

return true;

else if(way(x+1,y+1))//roght down

return true;

else if(way(x,y+1))//down

return true;

else if(way(x-1,y+1))//left down

return true;

else if(way(x-1,y))//left

return true;

else if(way(x-1,y-1))//left up

return true;

else//if all the direction can't go

{

maze[x][y]=3;

return false;

}

}//else if

else

return false;

}

































}