华为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);
    }
}
相关推荐
元周民1 天前
非厄米矩阵高精度计算预先判定需要的计算精度(matlab)
线性代数·matlab·矩阵
java修仙传1 天前
力扣hot100:搜索二维矩阵
算法·leetcode·矩阵
浅川.251 天前
xtuoj 矩阵
线性代数·矩阵
ACERT3331 天前
05-矩阵理论复习第五章 向量与矩阵范数
python·算法·矩阵
前端小白在前进1 天前
⭐力扣刷题:螺旋矩阵
算法·leetcode·矩阵
-一杯为品-2 天前
【机器人学|运动学与动力学】#1 齐次变换矩阵
线性代数·矩阵
胖咕噜的稞达鸭2 天前
算法入门:专题前缀和:一二维前缀和 寻找数组的中心下标 除自身以外数组的乘积 和为k的子数组 和可被k整除的子数组 连续数组 矩阵区域和
线性代数·算法·矩阵
拾贰_C2 天前
【数学 | 大学数学 | 考研数学 | 计算机】线性代数 | 矩阵论
线性代数·矩阵
qq_430855883 天前
线代第二章矩阵第四课:方阵的幂
算法·机器学习·矩阵
roman_日积跬步-终至千里3 天前
【计算机设计与算法-习题2】动态规划应用:矩阵乘法与钢条切割问题
算法·矩阵·动态规划