LC-1466. 重新规划路线(DFS、BFS)

1466. 重新规划路线

中等

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

路线用 connections 表示,其中 connections[i] = [a, b] 表示从城市 ab 的一条有向路线。

今年,城市 0 将会举办一场大型比赛,很多游客都想前往城市 0 。

请你帮助重新规划路线方向,使每个城市都可以访问城市 0 。返回需要变更方向的最小路线数。

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

示例 1:

img

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

示例 2:

img

输入: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 * 10^4
  • connections.length == n-1
  • connections[i].length == 2
  • 0 <= connections[i][0], connections[i][1] <= n-1
  • connections[i][0] != connections[i][1]

BFS

class Solution {
  /**
  构件图时标志是正边还是反边,一次bfs如果是反边则需要res+1
   */
    List<int[]>[] g;
    public int minReorder(int n, int[][] connections) {
        g = new ArrayList[n];
        Arrays.setAll(g, e -> new ArrayList<int[]>());
        for(int[] c : connections){
            int x = c[0], y = c[1];
            g[x].add(new int[]{y, -1}); // 1标志正边,-1标志反边
            g[y].add(new int[]{x, 1});
        }
        boolean[] vis = new boolean[n];
        Deque<Integer> dq = new ArrayDeque<>();
        dq.add(0);
        vis[0] = true;
        int res = 0;
        while(!dq.isEmpty()){
            int x = dq.pollLast();
            for(int[] q : g[x]){
                int y = q[0], dir = q[1];
                if(vis[y]) continue;
                vis[y] = true;
                if(dir == -1) res += 1;
                dq.addFirst(y);
            }
        }
        return res;
    }
}

DFS

class Solution {   
    List<int[]>[] g;
    int res = 0;
    boolean[] vis;
    public int minReorder(int n, int[][] connections) {
        g = new ArrayList[n];
        Arrays.setAll(g, e -> new ArrayList<int[]>());
        for(int[] c : connections){
            int x = c[0], y = c[1];
            g[x].add(new int[]{y, -1}); // 1标志正边,-1标志反边
            g[y].add(new int[]{x, 1});
        }
        vis = new boolean[n];
        dfs(0, -1);
        return res;
    }

    public void dfs(int x, int fa){
        vis[x] = true;
        for(int[] q : g[x]){
            int y = q[0], dir = q[1];
            if(vis[y]) continue;
            if(dir == -1) res += 1;
            dfs(y, x);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值