LeetCode_BFS_中等_1466.重新规划路线

目录

  • 1.题目
  • 2.思路
  • 3.代码实现(Java)

1.题目

n 座城市,从 0 到 n-1 编号,其间共有 n-1 条路线。因此,要想在两座不同城市之间旅行只有唯一一条路线可供选择(路线网形成一颗树)。去年,交通运输部决定重新规划路线,以改变交通拥堵的状况。路线用 connections 表示,其中 connections[i] = [a, b] 表示从城市 a 到 b 的一条有向路线。

今年,城市 0 将会举办一场大型比赛,很多游客都想前往城市 0 。请你帮助重新规划路线方向,使每个城市都可以访问城市 0。返回需要变更方向的最小路线数。

题目数据保证每个城市在重新规划路线方向后都能到达城市 0。

示例 1:

在这里插入图片描述

输入:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
输出:3
解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。

示例 2:

在这里插入图片描述

输入:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
输出:2
解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。

示例 3:
输入:n = 3, connections = [[1,0],[2,0]]
输出:0

提示:
2 <= n <= 5 * 104
connections.length == n - 1
connections[i].length == 2
0 <= connections[i][0], connections[i][1] <= n-1
connections[i][0] != connections[i][1]

2.思路

(1)BFS文章来源地址https://uudwc.com/A/gkpgg

3.代码实现(Java)

//思路1————BFS
class Solution {
    public int minReorder(int n, int[][] connections) {
        List<Integer>[] graph = buildGraph(n, connections);
        //以城市 0 为根节点,将城市之间的路线看作树,levels[i] 表示城市 i 所在的层数
        int[] levels = new int[n];
        Arrays.fill(levels, -1);
        //城市 0 在第 0 层
        levels[0] = 0;
        Queue<Integer> queue = new ArrayDeque<>();
        queue.offer(0);
        while (!queue.isEmpty()) {
            int city = queue.poll();
            for (int next : graph[city]) {
                if (levels[next] < 0) {
	                //更新当前城市所在的层数
                    levels[next] = levels[city] + 1;
                    queue.offer(next);
                }
            }
        }
        int res = 0;
        //计算需要调整的最小路线数
        for (int[] connection : connections) {
            if (levels[connection[0]] < levels[connection[1]]) {
                res++;
            }
        }
        return res;
    }

	//构建双向图的表示————邻接表
    public List<Integer>[] buildGraph(int n, int[][] connections) {
        ArrayList[] graph = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int[] connection : connections) {
            int a = connection[0];
            int b = connection[1];
            graph[a].add(b);
            graph[b].add(a);
        }
        return graph;
    }
}

原文地址:https://blog.csdn.net/weixin_43004044/article/details/131579596

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年07月07日 11:11
下一篇 2023年07月07日 11:12