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