bfs模板写
package 递归.递归进阶.bfs;
import java.util.LinkedList;
import java.util.Queue;
public class 扩散 {
static int[][] route = {
{0, 1},
{0, -1},
{1, 0},
{-1, 0}
};
static int[][] map;
public static void main(String[] args) {
map = new int[10000][10000];
int[][] temp = new int[10000][10000];
int ans = 0;
//初始化-1
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
map[i][j] = -1;
}
}
Queue<P> p_queue = new LinkedList<>();
p_queue.add(new P(2020, 2020, 0));
p_queue.add(new P(4040, 2031, 0));
p_queue.add(new P(2031, 2034, 0));
p_queue.add(new P(4020, 4020, 0));
while (!p_queue.isEmpty()) {
P p = p_queue.poll();
if (p.getStep() == 2020) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
if (map[i][j] == 1) {
ans++;
}
}
}
System.out.println(ans);
System.exit(0);
}
for (int i = 0; i < route.length; i++) {
int x1 = p.getX() + route[i][0];
int y1 = p.getY() + route[i][1];
if (map[x1][y1] == 1) continue;
map[x1][y1] = 1;
p_queue.add(new P(x1, y1, p.getStep() + 1));
}
}
}
}
class P {
private int x;
private int y;
private int step;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public P(int x, int y, int step) {
this.x = x;
this.y = y;
this.step = step;
}
}