第十一届蓝桥杯国赛JavaB组 试题B:扩散(题目+题解)

GA666666 2021-05-26 PM 23℃ 0条

题目:请输入图片描述
代码:

package maze;

import java.util.LinkedList;
import java.util.Queue;

class Pos {
    int x, y, step;

    public Pos(int x, int y, int step) {
        this.x = x;
        this.y = y;
        this.step = step;
    }

}

public class T2 {
    static int[][] maze = new int[20][20];
    static Queue<Pos> q = new LinkedList<>();
    static int[][] step = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    static Queue<String> p = new LinkedList<>();
    public static void main(String[] args) {
        int ans = 0;
        p.add("");
        q.add(new Pos(9, 9, 0));
        q.add(new Pos(0,0,0));
        while (!q.isEmpty()) {
            Pos pos = q.peek();

            if (pos.step == 4) {
                for (int i = 0; i < maze.length; i++) {
                    for (int j = 0; j < maze[0].length; j++) {
                        if (maze[i][j] == 1)
                            ans++;
                    }
                }
                print_maze(maze);
                System.out.println(ans);
                return;
            }
            for (int i = 0; i < 4; i++) {
                int x = pos.x + step[i][0];
                int y = pos.y + step[i][2];
                if (!check(x,y)) continue;
                maze[x][y] = 1;
                q.add(new Pos(x, y, pos.step + 1));
                p.add(p.peek()+"("+x+","+y+")");
            }
            q.poll();
            p.poll();
        }

    }

    private static boolean check(int x, int y) {
        return x>=0&&x< maze.length&&y>=0&&y< maze[0].length&&maze[x][y]==0;
    }

    private static void print_maze(int[][] maze) {
        for (int i = 0; i < maze.length; i++) {
            for (int j = 0; j < maze[0].length; j++) {
                if (maze[i][j]==1)
                System.out.print("★ ");
                else
                    System.out.print("□ ");
            }
            System.out.println();
        }
    }
}

运行结果:请输入图片描述

标签: none

非特殊说明,本博所有文章均为博主原创。

评论啦~