leetcode1466. 重新规划路线(dfs)

193 阅读1分钟

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

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

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

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

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

代码

class Solution {
    HashSet<Integer> visit=new HashSet<>();
    int ans=0;
    public int minReorder(int n, int[][] connections) {


        HashMap<Integer,List<Integer>> map=new HashMap<>();//无向图
        HashMap<Integer,HashSet<Integer>> map2=new HashMap<>();//有向图
        for(int i=0;i<n;i++)
        {
            map.put(i,new ArrayList<>());
            map2.put(i,new HashSet<>());
        }
        for(int[] net:connections)
        {
            map.get(net[1]).add(net[0]);
            map.get(net[0]).add(net[1]);
            map2.get(net[0]).add(net[1]);
        }//初始化有向图和无向图
        Reorder(0,map,map2);//从0开始
        return ans;
    }
    public void Reorder(int cur,  HashMap<Integer,List<Integer>> map,    HashMap<Integer,HashSet<Integer>> map2) {

        visit.add(cur);
        
        for(int next:map.get(cur))
        {
            if(!visit.contains(next))//是否被遍历
            {
                if(map2.get(cur).contains(next))//检查相邻节点的方向是否符合
                    ans++;

                Reorder(next,map,map2);
            }

        }
    }
}