力扣-图论-10【算法学习day.60】

前言

###我做这类文章一个重要的目的还是给正在学习的大家提供方向和记录学习过程(例如想要掌握基础用法,该刷哪些题?)我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!


习题

1.颜色交替的最短路径

题目链接: 1129. 颜色交替的最短路径 - 力扣(LeetCode)

题面:

贴上大佬代码:

java 复制代码
class Solution {
    public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {
        // 标明颜色,这是很好的习惯哦。
        final int RED = 0;
        final int BLUE = 1;

        // 构建双层邻接表
        List<Integer>[][] adj = new ArrayList[2][n];
        for (int i = 0; i < n; i++) {
            adj[RED][i] = new ArrayList<>();
            adj[BLUE][i] = new ArrayList<>();
        }
        for (int[] edge : redEdges) {
            adj[RED][edge[0]].add(edge[1]);
        }
        for (int[] edge : blueEdges) {
            adj[BLUE][edge[0]].add(edge[1]);
        }

        // 初始队列中同时含有蓝色源点和红色源点,并且我们也将相应颜色存入队列。
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[] {RED, 0});
        q.offer(new int[] {BLUE, 0});

        // 双层数组存储距离。
        int[][] dists = new int[2][n];
        Arrays.fill(dists[RED], Integer.MAX_VALUE);
        Arrays.fill(dists[BLUE], Integer.MAX_VALUE);
        dists[RED][0] = 0;
        dists[BLUE][0] = 0;

        while (!q.isEmpty()) {
            int[] current = q.poll();
            int uColor = current[0], u = current[1];
            int vColor = uColor ^ 1; // 异或切换 1 和 0,等同于 1 - uColor,得到下条边的颜色

            for (int v : adj[vColor][u]) {
                if (dists[vColor][v] != Integer.MAX_VALUE) continue;
                dists[vColor][v] = dists[uColor][u] + 1;
                q.offer(new int[] {vColor, v});
            }
        }

        // 将双层数组中的距离合并取小,无穷大改成 -1。
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = Math.min(dists[RED][i], dists[BLUE][i]);
            if (result[i] == Integer.MAX_VALUE) result[i] = -1;
        }
        return result;
    }
}

后言

上面是力扣图论专题,下一篇是其他的习题,希望有所帮助,一同进步,共勉!

相关推荐
qq_423233902 分钟前
C++与Python混合编程实战
开发语言·c++·算法
TracyCoder12312 分钟前
LeetCode Hot100(19/100)——206. 反转链表
算法·leetcode
m0_7155753414 分钟前
分布式任务调度系统
开发语言·c++·算法
Configure-Handler30 分钟前
buildroot System configuration
java·服务器·数据库
naruto_lnq36 分钟前
泛型编程与STL设计思想
开发语言·c++·算法
踩坑记录1 小时前
leetcode hot100 94. 二叉树的中序遍历 easy 递归 dfs
leetcode
zxsz_com_cn1 小时前
设备预测性维护算法分类及优劣势分析,选型指南来了
算法·分类·数据挖掘
:Concerto1 小时前
JavaSE 注解
java·开发语言·sprint