java-递归寻路

在这里插入图片描述

/*
	@author: fangweijie;
	@date: 2021-08-02;
	@title: mouse pathfinding
	@note:
		  "1"means we can go and "0" means we can't
		  "[1][1]" means the stating point ,"[6][5]" means the end point 
		  "2"means we passed the unit
*/

//maze
public class Maze{
	public static void main(String[] args) {
		/*
		create maze (use dim array),
		*/
		int mazeMap[][] = {	{0, 0, 0, 0, 0, 0, 0},
							{0, 1, 1, 1, 1, 1, 0},
							{0, 1, 1, 1, 1, 1, 0},
							{0, 0, 0, 1, 1, 1, 0},
							{0, 1, 1, 1, 1, 1, 0},
							{0, 1, 1, 1, 1, 1, 0},
							{0, 1, 1, 1, 1, 1, 0},
							{0, 0, 0, 0, 0, 0, 0}};
		Menthod M = new Menthod();
		boolean b = M.findWay(mazeMap, 1, 1);
		//output array
		for(int i = 0; i <= 7; i++){
			for(int j = 0; j <= 6; j++){
				System.out.print(mazeMap[i][j] + "\t");
			}
			System.out.print("\n");
		}
	}
}

class Menthod{
	public boolean findWay(int mazeMap[][], int i, int j){
		if(mazeMap[6][5] == 2){
			return true;
		}else{
			if(mazeMap[i][j] == 1){
				mazeMap[i][j] = 2;
				//Pouting firections have different priorities:
				//down->right->up->left \ up->right->down->left
				if(findWay(mazeMap, i+1, j)){
					return true;
				}else if(findWay(mazeMap, i, j+1)){
					return true;
				}else if(findWay(mazeMap, i-1, j)){
					return true;
				}else if(findWay(mazeMap, i, j-1)){
					return true;
				}else{
					mazeMap[i][j] = 3;
					return false;
				}
			}else{
				return false;
		}
			}
	}
}
运行结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值