华为OD机试真题-矩阵扩散-BFS(JAVA)

java 复制代码
import java.util.*;
/**
 * @version Ver 1.0
 * @date 2025/6/18
 * @description
 */
public class MatrixDiffusion {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] arrs = Arrays.stream(scanner.nextLine().split(",")).mapToInt(Integer::parseInt).toArray();
        int N = arrs[0];
        int M = arrs[1];
        int[][] matrix = new int[N][M];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if((i == arrs[2] && j == arrs[3])||(i == arrs[4] && j == arrs[5])){
                    matrix[i][j] = 1;
                }else{
                    matrix[i][j] = 0;
                }
            }
        }
        solve(matrix,arrs);
    }
    private static void solve(int[][] matrix, int[] arrs) {
        LinkedList<int[]> queue = new LinkedList<>();
        int[][] directions = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
        // 将起点加入队列
        queue.add(new int[]{arrs[2],arrs[3]});
        queue.add(new int[]{arrs[4],arrs[5]});
        int times = 0;
        while(!queue.isEmpty()){
            // 当前queue是否发生了扩散,由于一开始有两个起始点,两个起始点都可以同时扩散,所以将这两个起始点的扩散结果合并成一个,置于外层
            boolean flag = false;
            int size = queue.size();
            for(int j=0;j<size;j++){
                int[] ints = queue.poll();
                for(int i =0;i<4;i++){
                    int x = ints[0]+directions[i][0];
                    int y = ints[1]+directions[i][1];
                    if(x>=0 && x<arrs[0] && y>=0 && y<arrs[1] && matrix[x][y]==0){
                        matrix[x][y]=1;
                        queue.add(new int[]{x,y});
                        flag = true;
                    }
                }
            }
            if(flag){
                times++;
            }
        }
//        for (int i = 0; i < matrix.length; i++) {
//            for (int j = 0; j < matrix[0].length; j++) {
//                System.out.print(matrix[i][j]+" ");
//            }
//            System.out.println();
//        }

        System.out.println(times);
    }
}
相关推荐
汉克老师5 天前
GESP2023年12月认证C++二级( 第三部分编程题(2) 小杨的H字矩阵)
c++·算法·矩阵·循环结构·gesp二级·gesp2级
AI科技星5 天前
物理世界的几何建构:论统一场论的本体论革命与概念生成
人工智能·opencv·线性代数·算法·矩阵
没有bug.的程序员5 天前
订单系统重构史诗:从单体巨兽到微服务矩阵的演进、数据一致性内核与分布式事务
java·微服务·矩阵·重构·分布式事务·数据一致性·订单系统
super_lzb5 天前
【线性代数】矩阵第一讲:矩阵与矩阵的运算
线性代数·矩阵·考研数学·矩阵的计算
newbiai5 天前
TikTok矩阵账号引流怎么解决效率低成本高?
python·线性代数·矩阵
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
仟濹6 天前
【算法打卡day10(2026-02-24 周二)复习算法:DFS BFS 并查集】
算法·深度优先·图论·dfs·bfs·广度优先·宽度优先
We་ct6 天前
LeetCode 637. 二叉树的层平均值:BFS层序遍历实战解析
前端·数据结构·算法·leetcode·typescript·宽度优先
菜鸡儿齐6 天前
leetcode-搜索二维矩阵
算法·leetcode·矩阵
炽烈小老头6 天前
【每天学习一点算法 2026/02/24】矩阵置零
学习·算法·矩阵