关于BFS中内存超限的问题(Java)

在BFS中导致内存超限的根本原因就是入队次数过多,造成入队次数过多的原因很可能是重复入队,因此需检查自己的代码是否会出现重复入队的现象

例题 马的遍历 - 洛谷

 代码说明

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
public class Main {
	static int map[][];
	static int move[][]= {{1,2},{-1,2},{1,-2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
	static int m,n;
	static Queue<Horse> queue=new LinkedList<>();
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		m=sc.nextInt();
		map=new int[n][m];
        //地图初始化
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++) {
				map[i][j]=-1;
			}
		//获取马的初始坐标
		int x=sc.nextInt()-1;
		int y=sc.nextInt()-1;
		int step=0;
		
		bfs(x,y,step);
		
		for(int i=0;i<n;i++) {
				for(int j=0;j<m;j++) {
					System.out.printf("%-5d",map[i][j]);
				}
			System.out.println();
			}
	}
	public static void bfs(int x,int y,int step) {
		queue.offer(new Horse(x,y,step));
		map[x][y]=0;
		while(!queue.isEmpty()) {
 
            //出队,获取队首元素
			Horse temp=queue.poll();
			//map[temp.x][temp.y]=temp.step;//这样标记会导致内存超限,意思是马出队的时候再进行位置标记
			for(int i=0;i<8;i++) { 
			x=temp.x+move[i][0];
			 y=temp.y+move[i][1];
				if(check(x,y))
				{	
                    //正确标记方式,意思是入队的时候就进行位置标记了
					map[x][y]=temp.step+1;
 
					//入队一定要new一个对象否则会入队失败
					queue.offer(new Horse(x,y,temp.step+1));
				}	
			}
		}
	}
	//判断是否越界或是否走过
	static boolean check(int x,int y) {
		if(x<0||y<0||x>=n||y>=m||map[x][y]!=-1)
			return false;
		return true;
	}
	
	static class Horse{
	int x,y,step;
	public Horse() {
	}
	public Horse(int x,int y,int step) {
		this.x=x;
		this.y=y;
		this.step=step;
	}
}
}

错误做法的意思就是出队的时候再标记该位置,

正确做法应该是在入队的时候就要标记位置了,否则会导致重复入队.

这里通过图的广度遍历来说明区别

以下情况是出队的时候再标记,所以会导致重复入队

 以下情况是入队的时候就进行标记,所以就不会重复入队了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z菌君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值