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

发布于:2024-12-18 ⋅ 阅读:(59) ⋅ 点赞:(0)

前言

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


习题

1.颜色交替的最短路径

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

题面:

贴上大佬代码:

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;
    }
}

后言

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


网站公告

今日签到

点亮在社区的每一天
去签到