蓝桥杯十一届javab国赛扩散

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;
    }
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值