华为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);
    }
}
相关推荐
kobesdu1 天前
从零推导FAST-LIO的观测雅可比矩阵
人工智能·算法·矩阵
CreBee2 天前
CreBee功能大全:新媒体矩阵运营有哪些能力?
矩阵·新媒体运营·媒体
爱吃提升3 天前
MATLAB矩阵运算完全指南:从生成到索引操作
数据结构·matlab·矩阵
天天有money3 天前
API中转站在社媒矩阵里的价值:多平台文案如何统一改写
gpt·线性代数·ai·chatgpt·矩阵
哈德森hh3 天前
Twitter矩阵号怎么搭建?如何通过矩阵运营提升引流效果?
矩阵·twitter
小小帅呀3 天前
CUDA编程实战09:CUDA Graph 实战——降低重复 Kernel 与流水线提交开销
c++·人工智能·矩阵
良木林3 天前
矩阵 - LeetCode hot 100
线性代数·算法·leetcode·矩阵
小小帅呀3 天前
CUDA编程实战06:矩阵乘法优化——从朴素 GEMM 到共享内存分块
线性代数·矩阵
TKcloudmaster_H3 天前
规避风控稳运营!TK云大师定制脚本赋能TikTok矩阵规模化运营
大数据·人工智能·矩阵·自动化·新媒体运营·流量运营
起个破名想半天了3 天前
算法与数据结构之BFS广度优先遍历
数据结构·算法·bfs·宽度优先