鸣人和佐助广搜(Java)

在这里插入图片描述



import java.util.Scanner;

public class Main {

	static String[]  map;//其中@代表鸣人,+代表佐助。*代表通路,#代表大蛇丸的手下。
	//考虑到保存路径,所以就没有直接用队列,
	//而是用数组模拟的队列,这样能够将东西都保存起来而不弹出
	static step[] queue;
	static int[][] move = {{0,1},{0,-1},{1,0},{-1,0}};//移动的方向右左上下
	static int[][][] visit;//判重
	static int time;//需要花费的时间
	static class step{
		int x,y,pre;//pre存储父节点 的数组下标作为指针
		int k;//大蛇丸的个数
		public step(int x,int y,int pre,int k) {
			this.x=x;
			this.y=y;
			this.pre=pre;
			this.k=k;
		}
		public int getX() {
			return x;
		}
		public int getY() {
			return y;
		}
		public int getPre() {
			return pre;
		}
		public int getK() {
			return k;
		}
		
	}
	public static void main(String[] args) {
		Scanner reader=new Scanner(System.in);
		time=0;
		int N1=reader.nextInt();
		int N2=reader.nextInt();
		int k=reader.nextInt();
		int mingrenX=0,mingrenY=0,zuozuX=0,zuozuY=0;//鸣人和佐助的位置
		queue=new step[210*210];//疑问:队列的个数为什么最大为N1*N2?相当于递归回溯难道不应该会有很多结点吗?
		visit=new int[N1][N2][15];
		map=new String[N1];
		//对地图中的鸣人和佐助进行定位
		for(int i=0;i<N1;i++) {
				map[i]=reader.next();//读取每行的字符串
				for(int j=0;j<N2;j++) {
					if(map[i].charAt(j)=='@') {
						mingrenX=i;
						mingrenY=j;
					}
					if(map[i].charAt(j)=='+') {
						zuozuX=i;
						zuozuY=j;
					}
				}
					
		}
		
		int head=0,tail=0;
		queue[head]=new step(mingrenX, mingrenY,-1,k);
		visit[mingrenX][mingrenY][k]=1;
		tail++;
		boolean flag=false;
		while(head<tail) {
			flag=false;
			for(int i=0;i<4;i++) {
				int nx=queue[head].getX()+move[i][0];
				int ny=queue[head].getY()+move[i][1];
				//1、可行性剪枝:保证不越界
				if(nx >= 0 && nx < N1 && ny >= 0 && ny < N2  ) {
					//不是# 并且未访问过 
					if(map[nx].charAt(ny)!='#'&& visit[nx][ny][queue[head].getK()] == 0) {
						visit[nx][ny][queue[head].getK()]=1;
						queue[tail]=new step(nx, ny, head,queue[head].getK());
						tail++;
					}
					 //若为# 并且查克拉够 并且没访问过 可访问 
					if(map[nx].charAt(ny)=='#'&&queue[head].getK()>=1&&visit[nx][ny][queue[head].getK()-1]==0) {
						visit[nx][ny][queue[head].getK()-1]=1;
						queue[tail]=new step(nx, ny, head,queue[head].getK()-1);
						tail++;
					}
				}
				if(nx==zuozuX&&ny==zuozuY) {
					flag=true;
					break;
				}
			}
			if(flag) {
				print(queue[tail-1]);
				System.out.println(time);
				break;
			}
			head++;//假装弹出队列
		}
		if(!flag)System.out.println(-1);
		
	}
	static void  print(step s) {
		if(s.pre==-1) {
//			System.out.println("("+s.getX()+", "+s.getY()+", "+s.getK()+")");//这是打印路径
			return;
		}
		else {
			print(queue[s.getPre()]);
			time++;
//			System.out.println("("+s.getX()+", "+s.getY()+", "+s.getK()+")");//这是打印路径
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值