可以得出所有可行的路径
代码如下:
package Algorithm;
import java.util.LinkedList;
public class MiGong
{
public static void main(String[] args)
{
//0是可行的路径,1是墙壁,3是1起点,4是终点
int a[][]={
{1,1,1,1,1,1},
{3,0,0,0,0,1},
{1,0,1,1,0,1},
{1,0,1,1,0,1},
{1,0,0,0,0,1},
{1,0,1,1,0,1},
{1,0,1,1,0,1},
{1,0,0,0,0,4}
};
int ROW=a.length-1;
int COL=a[0].length-1;
LinkedList<LinkedList<String>> list=new LinkedList<LinkedList<String>>();//存放多条路径
LinkedList<String> list1=new LinkedList<String>();//存放临时的一条路径
list1.add("("+1+" "+0+")");
System.out.println(list1.get(0));
find(a,1,0,ROW,COL,list,list1);
System.out.println("可行的所有路径总数"+list.size());
for(LinkedList<String> listi:list)
{
for(String e:listi)
System.out.print(e);
System.out.println();
}
}
public static void find(int a[][],int x,int y,int ROW,int COL,LinkedList<LinkedList<String>> list,LinkedList<String> list1)
{
if(isOK(x+1,y,ROW,COL,a)&&!list1.contains("("+(x+1)+" "+y+")"))//下 未出界且未重复
{
LinkedList<String> temp=new LinkedList<String>();//创建临时的集合可以不需要return语句,也不用通过remove恢复到上一状态
for(String e:list1)
temp.add(e);
temp.add("("+(x+1)+" "+y+")");
if(a[x+1][y]==4)//找到终点
{
list.add(temp);
}
else find(a,x+1,y,ROW,COL,list,temp);//数字0 :表示是路
}
if(isOK(x-1,y,ROW,COL,a)&&!list1.contains("("+(x-1)+" "+y+")"))//上
{
LinkedList<String> temp=new LinkedList<String>();
for(String e:list1)
temp.add(e);
temp.add("("+(x-1)+" "+y+")");
if(a[x-1][y]==4)
{
list.add(temp);
}
else find(a,x-1,y,ROW,COL,list,temp);
}
if(isOK(x,y+1,ROW,COL,a)&&!list1.contains("("+x+" "+(y+1)+")"))//右
{
LinkedList<String> temp=new LinkedList<String>();
for(String e:list1)
temp.add(e);
temp.add("("+x+" "+(y+1)+")");
if(a[x][y+1]==4)
{
list.add(temp);
}
else find(a,x,y+1,ROW,COL,list,temp);
}
if(isOK(x,y-1,ROW,COL,a)&&!list1.contains("("+x+" "+(y-1)+")"))//左
{
LinkedList<String> temp=new LinkedList<String>();
for(String e:list1)
temp.add(e);
temp.add("("+x+" "+(y-1)+")");
if(a[x][y-1]==4)
{
list.add(temp);
}
else find(a,x,y-1,ROW,COL,list,temp);
}
}
public static boolean isOK(int x,int y,int ROW,int COL,int a[][])
{
if((x<=ROW&&x>=0&&y>=0&&y<=COL)&&(a[x][y]==0||a[x][y]==4))
return true;
else return false;
}
}