✅🚀 simple BFS Graph in all languages with easy explain code⤵️
please upvote for support 😊🧠 Problem Understanding:
You have an undirected weighted graph with n nodes.
You need to find the minimum edge weight in each connect
# *please upvote for support* 😊
# 🧠 Problem Understanding:
- You have an undirected weighted graph with n nodes.
- You need to find the minimum edge weight in each connected component.
   - For each query (s, e), return:
   -  The minimum edge weight if s and e are in the same component.
-1 if they are in different components
# 🔍 Example:
**Input:**
**n = 5
edges = [[0, 1, 4], [1, 2, 2], [3, 4, 1]]
queries = [[0, 2], [1, 3], [3, 4]]**
**0---1---4**
**3---4**
# Explanation:

- Components: {0, 1, 2} and {3, 4}
- Minimum edge weight in Component 1: min(4, 2) = 2
- Minimum edge weight in Component 2: 1
# Query results:
- (0, 2): Same component, min edge = 2
- (1, 3): Different components, result = -1
- (3, 4): Same component, min edge = 1
# Output: [2, -1, 1]
# 👷 Building the Graph:

- Create an adjacency list from the given edges.
-     🌐 Find Components:

- Use BFS to traverse each component.
-      Track the minimum edge weight for each component.
# 🔍 Answer Queries:

- Check if nodes belong to the same component.
- Return the minimum edge weight for the component or -1
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
     O(m+n+q)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
    O(n+m)
# Code
```cpp []
class Solution {
    private:
    int getcmpcost(int node, vector<vector<pair<int,int>>>&adj,vector<bool>&vis,vector<int>&cmp,int cid){
        queue<int>q;
        int ccost=INT_MAX;
        q.push(node);
        vis[node]=1;
        while(!q.empty()){
            int Node=q.front();
            q.pop();
            cmp[Node]=cid;
            for(auto [nbr,w]:adj[Node]){
                ccost&=w;
                if(vis[nbr])continue;
                vis[nbr]=1;
                q.push(nbr);
            }
        }
        return ccost;
    }
public:
    vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {
        vector<vector<pair<int,int>>>adj(n);
        for(auto ele:edges){
            adj[ele[0]].push_back({ele[1],ele[2]});
            adj[ele[1]].push_back({ele[0],ele[2]});
        }
        vector<bool>vis(n,0);
        vector<int>cmp(n);
        vector<int>cmpcost;
        int cid=0;
        for(int node=0;node<n;node++){
            if(!vis[node]){
                cmpcost.push_back(getcmpcost(node,adj,vis,cmp,cid));
                cid++;
            }
        }
        vector<int>ans;
        for(auto q:query){
            int s=q[0];
            int e=q[1];
            if(cmp[s]==cmp[e])ans.push_back(cmpcost[cmp[s]]);
            else ans.push_back(-1);
        }
        return ans;
    }
};
```
```python []
from collections import deque

def getcmpcost(node, adj, vis, cmp, cid):
    q = deque([node])
    vis[node] = True
    ccost = float('inf')

    while q:
        Node = q.popleft()
        cmp[Node] = cid

        for nbr, w in adj[Node]:
            ccost = min(ccost, w)
            if not vis[nbr]:
                vis[nbr] = True
                q.append(nbr)

    return ccost if ccost != float('inf') else -1

def minimumCost(n, edges, queries):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
        adj[v].append((u, w))

    vis = [False] * n
    cmp = [-1] * n
    cmpcost = []
    cid = 0

    for node in range(n):
        if not vis[node]:
            cmpcost.append(getcmpcost(node, adj, vis, cmp, cid))
            cid += 1

    result = []
    for s, e in queries:
        if cmp[s] == cmp[e]:
            result.append(cmpcost[cmp[s]])
        else:
            result.append(-1)

    return result
```
```java []
import java.util.*;

public class MinimumCost {
    private static int getCmpCost(int node, List<List<int[]>> adj, boolean[] vis, int[] cmp, int cid) {
        Queue<Integer> q = new LinkedList<>();
        q.add(node);
        vis[node] = true;
        int ccost = Integer.MAX_VALUE;

        while (!q.isEmpty()) {
            int current = q.poll();
            cmp[current] = cid;

            for (int[] neighbor : adj.get(current)) {
                int nbr = neighbor[0], weight = neighbor[1];
                ccost = Math.min(ccost, weight);

                if (!vis[nbr]) {
                    vis[nbr] = true;
                    q.add(nbr);
                }
            }
        }

        return ccost == Integer.MAX_VALUE ? -1 : ccost;
    }

    public static List<Integer> minimumCost(int n, int[][] edges, int[][] queries) {
        List<List<int[]>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());

        for (int[] edge : edges) {
            adj.get(edge[0]).add(new int[]{edge[1], edge[2]});
            adj.get(edge[1]).add(new int[]{edge[0], edge[2]});
        }

        boolean[] vis = new boolean[n];
        int[] cmp = new int[n];
        List<Integer> cmpCost = new ArrayList<>();
        int cid = 0;

        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                cmpCost.add(getCmpCost(i, adj, vis, cmp, cid));
                cid++;
            }
        }

        List<Integer> result = new ArrayList<>();
        for (int[] q : queries) {
            if (cmp[q[0]] == cmp[q[1]]) result.add(cmpCost.get(cmp[q[0]]));
            else result.add(-1);
        }

        return result;
    }
}
```
```js []
function getCmpCost(node, adj, vis, cmp, cid) {
    const queue = [node];
    vis[node] = true;
    let ccost = Infinity;

    while (queue.length) {
        const current = queue.shift();
        cmp[current] = cid;

        for (const [nbr, weight] of adj[current]) {
            ccost = Math.min(ccost, weight);
            if (!vis[nbr]) {
                vis[nbr] = true;
                queue.push(nbr);
            }
        }
    }

    return ccost === Infinity ? -1 : ccost;
}

function minimumCost(n, edges, queries) {
    const adj = Array.from({ length: n }, () => []);
    for (const [u, v, w] of edges) {
        adj[u].push([v, w]);
        adj[v].push([u, w]);
    }

    const vis = Array(n).fill(false);
    const cmp = Array(n).fill(-1);
    const cmpCost = [];
    let cid = 0;

    for (let i = 0; i < n; i++) {
        if (!vis[i]) {
            cmpCost.push(getCmpCost(i, adj, vis, cmp, cid));
            cid++;
        }
    }

    return queries.map(([s, e]) => (cmp[s] === cmp[e] ? cmpCost[cmp[s]] : -1));
}
```
```c# []
using System;
using System.Collections.Generic;

public class MinimumCost {
    private static int GetCmpCost(int node, List<List<(int, int)>> adj, bool[] vis, int[] cmp, int cid) {
        Queue<int> q = new Queue<int>();
        q.Enqueue(node);
        vis[node] = true;
        int ccost = int.MaxValue;

        while (q.Count > 0) {
            int current = q.Dequeue();
            cmp[current] = cid;

            foreach (var (nbr, weight) in adj[current]) {
                ccost = Math.Min(ccost, weight);

                if (!vis[nbr]) {
                    vis[nbr] = true;
                    q.Enqueue(nbr);
                }
            }
        }

        return ccost == int.MaxValue ? -1 : ccost;
    }

    public static List<int> MinimumCost(int n, int[][] edges, int[][] queries) {
        var adj = new List<List<(int, int)>>();
        for (int i = 0; i < n; i++) adj.Add(new List<(int, int)>());

        foreach (var edge in edges) {
            adj[edge[0]].Add((edge[1], edge[2]));
            adj[edge[1]].Add((edge[0], edge[2]));
        }

        bool[] vis = new bool[n];
        int[] cmp = new int[n];
        List<int> cmpCost = new List<int>();
        int cid = 0;

        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                cmpCost.Add(GetCmpCost(i, adj, vis, cmp, cid));
                cid++;
            }
        }

        var result = new List<int>();
        foreach (var q in queries) {
            result.Add(cmp[q[0]] == cmp[q[1]] ? cmpCost[cmp[q[0]]] : -1);
        }

        return result;
    }
}
```
``` go []
package main

import (
	"fmt"
	"math"
)

func getCmpCost(node int, adj [][][2]int, vis []bool, cmp []int, cid int) int {
	queue := []int{node}
	vis[node] = true
	ccost := math.MaxInt32

	for len(queue) > 0 {
		current := queue[0]
		queue = queue[1:]

		cmp[current] = cid

		for _, neighbor := range adj[current] {
			nbr, weight := neighbor[0], neighbor[1]
			ccost = int(math.Min(float64(ccost), float64(weight)))

			if !vis[nbr] {
				vis[nbr] = true
				queue = append(queue, nbr)
			}
		}
	}

	if ccost == math.MaxInt32 {
		return -1
	}
	return ccost
}

func minimumCost(n int, edges [][]int, queries [][]int) []int {
	adj := make([][][2]int, n)
	for _, edge := range edges {
		u, v, w := edge[0], edge[1], edge[2]
		adj[u] = append(adj[u], [2]int{v, w})
		adj[v] = append(adj[v], [2]int{u, w})
	}

	vis := make([]bool, n)
	cmp := make([]int, n)
	cmpCost := []int{}
	cid := 0

	for i := 0; i < n; i++ {
		if !vis[i] {
			cmpCost = append(cmpCost, getCmpCost(i, adj, vis, cmp, cid))
			cid++
		}
	}

	var result []int
	for _, q := range queries {
		s, e := q[0], q[1]
		if cmp[s] == cmp[e] {
			result = append(result, cmpCost[cmp[s]])
		} else {
			result = append(result, -1)
		}
	}

	return result
}
```
```php []
<?php
function getCmpCost($node, $adj, &$vis, &$cmp, $cid) {
    $queue = [$node];
    $vis[$node] = true;
    $ccost = PHP_INT_MAX;

    while (!empty($queue)) {
        $current = array_shift($queue);
        $cmp[$current] = $cid;

        foreach ($adj[$current] as $neighbor) {
            list($nbr, $weight) = $neighbor;
            $ccost = min($ccost, $weight);

            if (!$vis[$nbr]) {
                $vis[$nbr] = true;
                $queue[] = $nbr;
            }
        }
    }

    return $ccost === PHP_INT_MAX ? -1 : $ccost;
}

function minimumCost($n, $edges, $queries) {
    $adj = array_fill(0, $n, []);
    foreach ($edges as $edge) {
        $adj[$edge[0]][] = [$edge[1], $edge[2]];
        $adj[$edge[1]][] = [$edge[0], $edge[2]];
    }

    $vis = array_fill(0, $n, false);
    $cmp = array_fill(0, $n, -1);
    $cmpCost = [];
    $cid = 0;

    for ($i = 0; $i < $n; $i++) {
        if (!$vis[$i]) {
            $cmpCost[] = getCmpCost($i, $adj, $vis, $cmp, $cid);
            $cid++;
        }
    }

    $result = [];
    foreach ($queries as $query) {
        [$s, $e] = $query;
        $result[] = $cmp[$s] === $cmp[$e] ? $cmpCost[$cmp[$s]] : -1;
    }

    return $result;
}
?>
```
``` kotlin []
import java.util.*

fun getCmpCost(node: Int, adj: List<MutableList<Pair<Int, Int>>>, vis: BooleanArray, cmp: IntArray, cid: Int): Int {
    val queue: Queue<Int> = LinkedList()
    queue.add(node)
    vis[node] = true
    var ccost = Int.MAX_VALUE

    while (queue.isNotEmpty()) {
        val current = queue.poll()
        cmp[current] = cid

        for ((nbr, weight) in adj[current]) {
            ccost = minOf(ccost, weight)

            if (!vis[nbr]) {
                vis[nbr] = true
                queue.add(nbr)
            }
        }
    }

    return if (ccost == Int.MAX_VALUE) -1 else ccost
}

fun minimumCost(n: Int, edges: Array<IntArray>, queries: Array<IntArray>): List<Int> {
    val adj = List(n) { mutableListOf<Pair<Int, Int>>() }
    for (edge in edges) {
        adj[edge[0]].add(edge[1] to edge[2])
        adj[edge[1]].add(edge[0] to edge[2])
    }

    val vis = BooleanArray(n)
    val cmp = IntArray(n)
    val cmpCost = mutableListOf<Int>()
    var cid = 0

    for (i in 0 until n) {
        if (!vis[i]) {
            cmpCost.add(getCmpCost(i, adj, vis, cmp, cid))
            cid++
        }
    }

    return queries.map { (s, e) ->
        if (cmp[s] == cmp[e]) cmpCost[cmp[s]] else -1
    }
}
```
```ruby []
def get_cmp_cost(node, adj, vis, cmp, cid)
  queue = [node]
  vis[node] = true
  ccost = Float::INFINITY

  until queue.empty?
    current = queue.shift
    cmp[current] = cid

    adj[current].each do |nbr, weight|
      ccost = [ccost, weight].min

      unless vis[nbr]
        vis[nbr] = true
        queue << nbr
      end
    end
  end

  ccost == Float::INFINITY ? -1 : ccost
end

def minimum_cost(n, edges, queries)
  adj = Array.new(n) { [] }
  edges.each { |u, v, w| adj[u] << [v, w]; adj[v] << [u, w] }

  vis = Array.new(n, false)
  cmp = Array.new(n)
  cmp_cost = []
  cid = 0

  (0...n).each do |i|
    unless vis[i]
      cmp_cost << get_cmp_cost(i, adj, vis, cmp, cid)
      cid += 1
    end
  end

  queries.map { |s, e| cmp[s] == cmp[e] ? cmp_cost[cmp[s]] : -1 }
end
```
```swift []
func getCmpCost(_ node: Int, _ adj: [[(Int, Int)]], _ vis: inout [Bool], _ cmp: inout [Int], _ cid: Int) -> Int {
    var queue = [node]
    vis[node] = true
    var ccost = Int.max

    while !queue.isEmpty {
        let current = queue.removeFirst()
        cmp[current] = cid

        for (nbr, weight) in adj[current] {
            ccost = min(ccost, weight)
            if !vis[nbr] {
                vis[nbr] = true
                queue.append(nbr)
            }
        }
    }

    return ccost == Int.max ? -1 : ccost
}

func minimumCost(_ n: Int, _ edges: [[Int]], _ queries: [[Int]]) -> [Int] {
    var adj = Array(repeating: [(Int, Int)](), count: n)
    for edge in edges {
        adj[edge[0]].append((edge[1], edge[2]))
        adj[edge[1]].append((edge[0], edge[2]))
    }

    var vis = Array(repeating: false, count: n)
    var cmp = Array(repeating: 0, count: n)
    var cmpCost = [Int]()
    var cid = 0

    for i in 0..<n where !vis[i] {
        cmpCost.append(getCmpCost(i, adj, &vis, &cmp, cid))
        cid += 1
    }

    return queries.map { cmp[$0[0]] == cmp[$0[1]] ? cmpCost[cmp[$0[0]]] : -1 }
}
```
![image.png](https://assets.leetcode.com/users/images/2d0faa93-60b5-4411-8eec-0caaa98590f8_1742441885.1595266.png)


['Swift', 'Python', 'C++', 'Java', 'Go', 'Rust', 'Ruby', 'Kotlin', 'JavaScript', 'C#']