迷宫实现算法:
package algrithm;
import java.util.Scanner;
public class maze {
public static void main(String[] args)
{
int a[][]={{1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,1},
{1,1,0,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,1,0,1},
{1,1,0,1,0,0,1,1,0,0,0,1},
{1,1,1,1,1,1,1,1,1,0,1,1},
{1,0,0,0,0,0,0,0,1,0,0,1},
{1,1,1,1,1,1,1,1,0,0,1,1},
{1,1,0,0,1,0,1,0,0,1,0,1},
{1,0,1,0,0,1,0,1,0,1,0,1},
{1,0,0,1,0,0,1,1,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1}};
System.out.println("the maze is:");
print(a);
Scanner sc=new Scanner(System.in);
System.out.println("please input enter coordinate:");
int xstart=sc.nextInt();
int ystart=sc.nextInt();
System.out.println("please input exit coordinate:");
int xend=sc.nextInt();
int yend=sc.nextInt();
System.out.println("纵向为x轴,横向为y轴!");
path(a,xstart,ystart,xend,yend);
}
public static void path(int a[][],int xstart,int ystart,int xend,int yend)
{
cStackList cs=new cStackList();
cs.push(xstart, ystart);//入口坐标入栈
int x=xstart;
int y=ystart;
a[x][y]=2; //将已走过的坐标置为2
while(!cs.isEmpty())
{
cStack temp=cs.peek();
x=temp.xData;
y=temp.yData;
if(temp.xData==xend&&temp.yData==yend)//如果找到路径
{
System.out.println("find the path!the coordinate is:");
break;
}
if(a[x][y-1]==0)//向左移动
{
cs.push(x,y-1);
a[x][y-1]=2; //将已走过的坐标置为2
x=x;
y=y-1;
}
else
{
if(a[x][y+1]==0)//向右移动
{
cs.push(x, y+1);
a[x][y+1]=2;
x=x;
y=y+1;
}
else
if(a[x-1][y]==0)//向上移动
{
cs.push(x-1, y);
a[x-1][y]=2;
x=x-1;
y=y;
}
else
if(a[x+1][y]==0)//向下移动
{
cs.push(x+1, y);
a[x+1][y]=2;
x=x+1;
y=y;
}
else
{
cs.pop();//如果4个方向都走不通,则往后退一步
}
}
}
if(cs.isEmpty())//如果找不到路径
{
System.out.println("no way!");
}
cStackList cc=new cStackList();
while(!cs.isEmpty())
{
cStack cst=cs.pop();
cc.push(cst.xData, cst.yData);
}
cc.displayList();//输出路径
}
public static void print(int a[][])
{
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
class cStack
{
public int xData;
public int yData;
public cStack next;
public cStack(int x,int y)
{
xData = x;
yData = y;
}
public void display()
{
System.out.print("("+xData+","+yData+")"+"->");
}
}
class cStackList
{
private cStack top;
public cStackList()
{
top=null;
}
public boolean isEmpty()
{
return (top==null);
}
public cStack peek()
{
return top;
}
public void push(int x,int y)
{
cStack newcStack=new cStack(x,y);
newcStack.next=top;
top=newcStack;
}
public cStack pop()
{
cStack temp=top;
top=top.next;
return temp;
}
public void displayList()
{
cStack current=top;
while(current!=null)
{
current.display();
current=current.next;
}
}
}