华为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);
    }
}
相关推荐
】余185381628003 小时前
矩阵系统源码搭建与定制化开发,支持OEM
线性代数·矩阵
YuTaoShao1 天前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
Kaltistss2 天前
240.搜索二维矩阵Ⅱ
线性代数·算法·矩阵
YOLO大师2 天前
华为OD机试 2025B卷 - 小明减肥(C++&Python&JAVA&JS&C语言)
c++·python·华为od·华为od机试·华为od2025b卷·华为机试2025b卷·华为od机试2025b卷
说私域2 天前
视频号账号矩阵运营中定制开发开源 AI 智能名片 S2B2C 商城小程序的赋能研究
人工智能·矩阵·开源
张晓~183399481213 天前
数字人源码部署流程分享--- PC+小程序融合方案
javascript·小程序·矩阵·aigc·文心一言·html5
闻缺陷则喜何志丹3 天前
【BFS】 P10864 [HBCPC2024] Genshin Impact Startup Forbidden II|普及+
c++·算法·宽度优先·洛谷
我爱C编程3 天前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
CVer儿3 天前
svd分解求旋转平移矩阵
线性代数·算法·矩阵
张晓~183399481214 天前
数字人分身+矩阵系统聚合+碰一碰发视频: 源码搭建-支持OEM
线性代数·矩阵·音视频