在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;
}
}
}
错误做法的意思就是出队的时候再标记该位置,
正确做法应该是在入队的时候就要标记位置了,否则会导致重复入队.
这里通过图的广度遍历来说明区别
以下情况是出队的时候再标记,所以会导致重复入队
以下情况是入队的时候就进行标记,所以就不会重复入队了