Minimum Score of a Path Between Two Cities - 2492
Wed Mar 22 2023 16:34:51 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
class Solution {
public int minScore(int n, int[][] roads) {
/*question of connected components , find 1's component and find minimum edge
weight in 1's component as we have to find path between 1 and n
*/
//making adjency list
HashMap<Integer, ArrayList<List<Integer>>> map = new HashMap<>();
for(int[] road : roads){
map.computeIfAbsent(road[0],k -> new ArrayList<List<Integer>>()).add(Arrays.asList(road[1],road[2]));
map.computeIfAbsent(road[1],k -> new ArrayList<List<Integer>>()).add(Arrays.asList(road[0],road[2]));
}
System.out.println(map);
return BFS(n , map);
}
public int BFS(int n , HashMap<Integer, ArrayList<List<Integer>>> map){
int ans = Integer.MAX_VALUE;
Queue<Integer> q = new ArrayDeque<>();
boolean visited[] = new boolean[n+1];
//adding first node
q.add(1);
visited[1] = true;
while(q.size()!=0){
int node = q.poll(); //remove
//work and then add into q
//if(map.containsKey(node)==false) continue;
for(List<Integer> edge : map.get(node)){
ans = Math.min(ans , edge.get(1));
if(visited[edge.get(0)]==false){
q.add(edge.get(0));
visited[edge.get(0)] = true;
}
}
}
return ans;
}
}
content_copyCOPY
https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/description/
Comments