华为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);
    }
}
相关推荐
Tisfy2 小时前
LeetCode 1594.矩阵的最大非负积:动态规划O(mn)
leetcode·矩阵·动态规划·dp
Frostnova丶2 小时前
LeetCode 1594.矩阵中最大的非负乘积
算法·leetcode·矩阵
sheeta19982 小时前
LeetCode 每日一题笔记 日期:2025.03.22 题目:1886.判断矩阵经轮转后是否一致
笔记·leetcode·矩阵
带娃的IT创业者2 小时前
意图识别与工具智能路由:17 维关键词矩阵如何让 LLM 精准选择 38 个工具
线性代数·矩阵
Zero3 小时前
机器学习线性代数--(7)逆矩阵、列空间、秩、零空间与非方阵
线性代数·机器学习·矩阵
窝子面3 小时前
LeetCode练题六:dfs与bfs
leetcode·深度优先·宽度优先
lihihi3 小时前
P10474 [ICPC 2011 Beijing R] Matrix 矩阵哈希
矩阵·哈希算法
爱喝纯牛奶的柠檬19 小时前
基于STM32的4*4矩阵软键盘驱动
stm32·嵌入式硬件·矩阵
Frostnova丶19 小时前
LeetCode 48 & 1886.矩阵旋转与判断
算法·leetcode·矩阵
阿Y加油吧1 天前
力扣打卡——搜索二维矩阵、相交链表
线性代数·leetcode·矩阵