迷宫问题

定义一个二维数组: 


int maze[5][5] = {


0, 1, 0, 0, 0,


0, 1, 0, 1, 0,


0, 0, 0, 0, 0,


0, 1, 1, 1, 0,


0, 0, 0, 1, 0,


};

 

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

 

 

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

 

 

Output

左上角到右下角的最短路径,格式如样例所示。

 

 

Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0

0 0 0 1 0

 

Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)

(3, 4)

 

 

 

 

 

import java.util.*;
public class Main{
	
	static ArrayList<A> A;
	static int x[][],y[][],num;
	
	
	public static void main(String args[]){
		Scanner reader=new Scanner(System.in);
		x=new int[5][5];
		y=new int[5][5];
		A=new ArrayList<A>();
		for(int n=0;n<5;n++){
			for(int m=0;m<5;m++){
				x[n][m]=reader.nextInt();
			}
		}
		A xx=new A();
		xx.x=0;
		xx.y=0;
		xx.step=0;
		A.add(xx);
		f();
		A.clear();
		num=y[4][4];
		//System.out.println(num);
		ff(4,4);
		for(int n=A.size()-1;n>=0;n--){
			System.out.println("("+A.get(n).x+", "+A.get(n).y+")");
		}
		//System.out.println(num);
	}
	
	public static void f(){
	    for(;;){
	    	A xx=A.get(0);
			A.remove(0);
			if(xx.x==4&&xx.y==4)break;
			if(xx.x+1<5&&x[xx.x+1][xx.y]==0&&y[xx.x+1][xx.y]==0){
				y[xx.x+1][xx.y]=xx.step+1;
				A yy=new A();
				yy.x=xx.x+1;
				yy.y=xx.y;
				yy.step=xx.step+1;
				A.add(yy);
			}
			if(xx.y+1<5&&x[xx.x][xx.y+1]==0&&y[xx.x][xx.y+1]==0){
				y[xx.x][xx.y+1]=xx.step+1;
				A yy=new A();
				yy.x=xx.x;
				yy.y=xx.y+1;
				yy.step=xx.step+1;
				A.add(yy);
			}
			if(xx.x-1>=0&&x[xx.x-1][xx.y]==0&&y[xx.x-1][xx.y]==0){
				y[xx.x-1][xx.y]=xx.step+1;
				A yy=new A();
				yy.x=xx.x-1;
				yy.y=xx.y;
				yy.step=xx.step+1;
				A.add(yy);
			}
			if(xx.y-1>=0&&x[xx.x][xx.y-1]==0&&y[xx.x][xx.y-1]==0){
				y[xx.x][xx.y-1]=xx.step+1;
				A yy=new A();
				yy.x=xx.x;
				yy.y=xx.y-1;
				yy.step=xx.step+1;
				A.add(yy);
			}
	    }
	}
	
	public static void ff(int a,int b){
		A xx=new A();
		//System.out.println(a+" "+b+" "+y[a][b]+" "+num);
		if((a==1&&b==0)||(a==0&&b==1)){
			A xxx=new A();
			xxx.x=a;
			xxx.y=b;
			A.add(xxx);
			xx.x=0;
			xx.y=0;
			A.add(xx);
			return;
		}
		if(a+1<5&&y[a+1][b]==y[a][b]-1){
			num--;
			xx.x=a;
			xx.y=b;
			A.add(xx);
			ff(a+1,b);
		}
		if(b+1<5&&y[a][b+1]==y[a][b]-1){
			num--;
			xx.x=a;
			xx.y=b;
			A.add(xx);
			ff(a,b+1);
		}	
		if(a-1>=0&&y[a-1][b]==y[a][b]-1){
			num--;
			xx.x=a;
			xx.y=b;
			A.add(xx);
			ff(a-1,b);
		}	
		if(b-1>=0&&y[a][b-1]==y[a][b]-1){
			num--;
			xx.x=a;
			xx.y=b;
			A.add(xx);
			ff(a,b-1);
		}	
			
		
		return;
	}
	
}

class A{
	int x;
	int y;
	int step;
}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值