There are
Roads are represented by
This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.
It's guaranteed that each city can reach the city 0 after reorder.
n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.Roads are represented by
connections where connections[i] = [a, b] represents a road from the city a to b.This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.
It's guaranteed that each city can reach the city 0 after reorder.
Example 1:
Input: n = 5, connections ={{1,0},{1,2},{3,2},{3,4}}
Output: 2Approach
Java
import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;public class ReorderRoutes {public static void main(String[] args) {int n = 5;int[][] connections = { { 1, 0 }, { 1, 2 }, { 3, 2 }, { 3, 4 } };System.out.println(minReorder(n, connections));}static int minReorder(int n, int[][] connections) {List<List<Integer>> arr = new ArrayList<List<Integer>>();List<List<Integer>> tr = new ArrayList<List<Integer>>();// initialization the listfor (int i = 0; i < connections.length+1; i++) {arr.add(new ArrayList<Integer>());tr.add(new ArrayList<Integer>());}int vis[] = new int[n];// create the transpose graph// and graphfor (int i = 0; i < connections.length; i++) {int a = connections[i][0];int b = connections[i][1];arr.get(a).add(b);tr.get(b).add(a);}Queue<Integer> q = new LinkedList<>();q.add(0);int res = 0;// iterate till the queue is not// emptywhile (!q.isEmpty()) {int curr = q.poll();vis[curr] = 1;for (int child : arr.get(curr)) {if (vis[child] == 0) {res++;q.add(child);}}for (int child : tr.get(curr)) {if (vis[child] == 0) {q.add(child);}}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;int minReorder(int n, vector<vector<int>>& connections){vector<vector<int>> arr(n),tr(n);vector<int> vis(n);//create the transpose graph//and graphfor(int i=0;i<connections.size();i++){int a=connections[i][0];int b=connections[i][1];arr[a].push_back(b);tr[b].push_back(a);}queue<int> q;q.push(0);int res=0;//iterate till the queue is not//emptywhile(!q.empty()){int curr=q.front();q.pop();vis[curr]=1;for(int child:arr[curr]){if(vis[child]==0){res++;q.push(child);}}for(int child:tr[curr]){if(vis[child]==0){q.push(child);}}}return res;}int main(){int n = 5;vector<vector<int>> connections ={{1,0},{1,2},{3,2},{3,4}};cout<<minReorder(n,connections);return 0;}
No comments:
Post a Comment