leetcode1466. 重新规划路线(dfs)
生活随笔
收集整理的這篇文章主要介紹了
leetcode1466. 重新规划路线(dfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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);}}} }總結
以上是生活随笔為你收集整理的leetcode1466. 重新规划路线(dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到蟾蜍是什么意思周公解梦
- 下一篇: 梦到牙齿松动拔牙是什么预兆