Skip to content

Commit 6313001

Browse files
authored
Merge pull request codeharborhub#1636 from SadafKausar2025/mc
Added leetcode 3108-Minimum-cost-walk-in-weighted-graph
2 parents dfa68e8 + 7cda5a1 commit 6313001

File tree

4 files changed

+383
-1
lines changed

4 files changed

+383
-1
lines changed

dsa-problems/leetcode-problems/3100-3199.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export const problems = [
6262
"problemName": "3108. Minimum Cost Walk in Weighted Graph",
6363
"difficulty": "Hard",
6464
"leetCodeLink": "https://leetcode.com/problems/minimum-cost-walk-in-weighted-graph",
65-
"solutionLink": "#"
65+
"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Minimum-cost-walk-in-weighted-graph"
6666
},
6767
{
6868
"problemName": "3109. Find the Index of Permutation",
Lines changed: 382 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,382 @@
1+
---
2+
id: Minimum-cost-walk-in-weighted-graph
3+
title: Minimum-cost-walk-in-weighted-graph
4+
sidebar_label: 3108-Minimum-cost-walk-in-weighted-graph
5+
tags:
6+
- Java
7+
- Greedy
8+
- String
9+
description: "This document provides a solution of Minimum-cost-walk-in-weighted-graph"
10+
---
11+
12+
## Problem Statement:
13+
14+
There is an undirected weighted graph with n vertices labeled from 0 to n - 1.
15+
16+
You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi.
17+
18+
A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.
19+
20+
The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where & denotes the bitwise AND operator.
21+
22+
You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no such walk, the answer is -1.
23+
24+
Return the array answer, where answer[i] denotes the minimum cost of a walk for query i.
25+
26+
**Example 1:**
27+
28+
Input: n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]
29+
Output: [1,-1]
30+
31+
Explanation:
32+
33+
![alt text](image-3.png)
34+
35+
To achieve the cost of 1 in the first query, we need to move on the following edges: 0->1 (weight 7), 1->2 (weight 1), 2->1 (weight 1), 1->3 (weight 7).
36+
37+
In the second query, there is no walk between nodes 3 and 4, so the answer is -1.
38+
39+
**Example 2:**
40+
41+
Input: n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]
42+
Output: [0]
43+
44+
Explanation:
45+
![alt text](image-4.png)
46+
47+
To achieve the cost of 0 in the first query, we need to move on the following edges: 1->2 (weight 1), 2->1 (weight 6), 1->2 (weight 1).
48+
49+
**Constraints:**
50+
51+
`2 <= n <= 105`
52+
`0 <= edges.length <= 105`
53+
`edges[i].length == 3`
54+
`0 <= ui, vi <= n - 1`
55+
`ui != vi`
56+
`0 <= wi <= 105`
57+
`1 <= query.length <= 105`
58+
`query[i].length == 2`
59+
`0 <= si, ti <= n - 1`
60+
`si != ti`
61+
62+
## Solutions:
63+
64+
### Intuition
65+
66+
The problem requires finding the minimum cost of a walk in an undirected weighted graph where the cost is defined as the bitwise AND of the weights of the edges traversed during the walk. We need to handle multiple queries for different starting and ending vertices.
67+
68+
### Approach
69+
70+
1. Construct the adjacency list representation of the graph and initialize the cost array c.
71+
72+
2. For each edge, update the cost array c by performing bitwise AND with the edge weight.
73+
74+
3. Use a breadth-first search (BFS) traversal to find connected components in the graph and update the cost array c for each component.
75+
76+
4. For each query, check if the starting and ending vertices belong to the same connected component. If they do, return the minimum cost of the connected component; otherwise, return -1.
77+
78+
## code:
79+
80+
<Tabs>
81+
<TabItem value="cpp" label="C++" default>
82+
<SolutionAuthor name="@Ajay-Dhangar"/>
83+
```cpp
84+
#include <vector>
85+
#include <queue>
86+
#include <limits.h>
87+
using namespace std;
88+
89+
class Solution {
90+
public:
91+
vector<int> minimumCost(int N, vector<vector<int>>& edges, vector<vector<int>>& queries) {
92+
vector<vector<int>> adj(N); // Adjacency list
93+
vector<int> c(N, INT_MAX); // Cost array, initialized with maximum possible value
94+
95+
// Construct adjacency list and update cost array
96+
for (vector<int> edge : edges) {
97+
int u = edge[0], v = edge[1], k = edge[2];
98+
adj[u].push_back(v);
99+
adj[v].push_back(u);
100+
c[u] = c[u] & k; // Update cost with bitwise AND
101+
c[v] = c[v] & k;
102+
}
103+
104+
// BFS to find connected components and update cost array for each component
105+
queue<int> q;
106+
vector<int> group(N, -1); // Group array to store component group of each vertex
107+
for (int i = 0; i < N; i++) {
108+
if (group[i] == -1) {
109+
group[i] = i; // Assign component group ID
110+
q.push(i);
111+
while (!q.empty()) {
112+
int u = q.front(); q.pop();
113+
c[i] = c[i] & c[u]; // Update cost with bitwise AND of all vertices in the component
114+
for (int v : adj[u]) {
115+
if (group[v] == -1) {
116+
group[v] = i;
117+
q.push(v);
118+
}
119+
}
120+
}
121+
}
122+
}
123+
124+
// Process queries
125+
vector<int> res;
126+
for (vector<int> query : queries) {
127+
int s = query[0], t = query[1];
128+
if (s == t) {
129+
res.push_back(0); // Same starting and ending vertex
130+
} else {
131+
if (group[s] == group[t]) {
132+
res.push_back(c[group[s]]); // Same connected component
133+
} else {
134+
res.push_back(-1); // Different connected components
135+
}
136+
}
137+
}
138+
return res;
139+
}
140+
};
141+
```
142+
</TabItem>
143+
<TabItem value="java" label="Java">
144+
<SolutionAuthor name="@Ajay-Dhangar"/>
145+
```java
146+
import java.util.*;
147+
148+
public class Solution {
149+
public List<Integer> minimumCost(int N, List<List<Integer>> edges, List<List<Integer>> queries) {
150+
List<List<Integer>> adj = new ArrayList<>(N); // Adjacency list
151+
for (int i = 0; i < N; i++) adj.add(new ArrayList<>());
152+
int[] c = new int[N]; // Cost array, initialized with maximum possible value
153+
Arrays.fill(c, Integer.MAX_VALUE);
154+
155+
// Construct adjacency list and update cost array
156+
for (List<Integer> edge : edges) {
157+
int u = edge.get(0), v = edge.get(1), k = edge.get(2);
158+
adj.get(u).add(v);
159+
adj.get(v).add(u);
160+
c[u] &= k; // Update cost with bitwise AND
161+
c[v] &= k;
162+
}
163+
164+
// BFS to find connected components and update cost array for each component
165+
Queue<Integer> q = new LinkedList<>();
166+
int[] group = new int[N]; // Group array to store component group of each vertex
167+
Arrays.fill(group, -1);
168+
for (int i = 0; i < N; i++) {
169+
if (group[i] == -1) {
170+
group[i] = i; // Assign component group ID
171+
q.offer(i);
172+
while (!q.isEmpty()) {
173+
int u = q.poll();
174+
c[i] &= c[u]; // Update cost with bitwise AND of all vertices in the component
175+
for (int v : adj.get(u)) {
176+
if (group[v] == -1) {
177+
group[v] = i;
178+
q.offer(v);
179+
}
180+
}
181+
}
182+
}
183+
}
184+
185+
// Process queries
186+
List<Integer> res = new ArrayList<>();
187+
for (List<Integer> query : queries) {
188+
int s = query.get(0), t = query.get(1);
189+
if (s == t) {
190+
res.add(0); // Same starting and ending vertex
191+
} else {
192+
if (group[s] == group[t]) {
193+
res.add(c[group[s]]); // Same connected component
194+
} else {
195+
res.add(-1); // Different connected components
196+
}
197+
}
198+
}
199+
return res;
200+
}
201+
}
202+
```
203+
</TabItem>
204+
<TabItem value="python" label="Python">
205+
<SolutionAuthor name="@Ajay-Dhangar"/>
206+
```python
207+
from typing import List
208+
from collections import deque
209+
210+
class Solution:
211+
def minimumCost(self, N: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:
212+
adj = [[] for _ in range(N)] # Adjacency list
213+
c = [float('inf')] * N # Cost array, initialized with maximum possible value
214+
215+
# Construct adjacency list and update cost array
216+
for u, v, k in edges:
217+
adj[u].append(v)
218+
adj[v].append(u)
219+
c[u] &= k # Update cost with bitwise AND
220+
c[v] &= k
221+
222+
# BFS to find connected components and update cost array for each component
223+
q = deque()
224+
group = [-1] * N # Group array to store component group of each vertex
225+
for i in range(N):
226+
if group[i] == -1:
227+
group[i] = i # Assign component group ID
228+
q.append(i)
229+
while q:
230+
u = q.popleft()
231+
c[i] &= c[u] # Update cost with bitwise AND of all vertices in the component
232+
for v in adj[u]:
233+
if group[v] == -1:
234+
group[v] = i
235+
q.append(v)
236+
237+
# Process queries
238+
res = []
239+
for s, t in queries:
240+
if s == t:
241+
res.append(0) # Same starting and ending vertex
242+
else:
243+
if group[s] == group[t]:
244+
res.append(c[group[s]]) # Same connected component
245+
else:
246+
res.append(-1) # Different connected components
247+
return res
248+
```
249+
</TabItem>
250+
<TabItem value="c" label="C">
251+
<SolutionAuthor name="@Ajay-Dhangar"/>
252+
```c
253+
#include <stdio.h>
254+
#include <stdlib.h>
255+
#include <limits.h>
256+
#include <string.h>
257+
#include <stdbool.h>
258+
259+
typedef struct {
260+
int* data;
261+
int front;
262+
int rear;
263+
int size;
264+
int capacity;
265+
} Queue;
266+
267+
Queue* createQueue(int capacity) {
268+
Queue* queue = (Queue*)malloc(sizeof(Queue));
269+
queue->capacity = capacity;
270+
queue->front = queue->size = 0;
271+
queue->rear = capacity - 1;
272+
queue->data = (int*)malloc(queue->capacity * sizeof(int));
273+
return queue;
274+
}
275+
276+
bool isFull(Queue* queue) {
277+
return (queue->size == queue->capacity);
278+
}
279+
280+
bool isEmpty(Queue* queue) {
281+
return (queue->size == 0);
282+
}
283+
284+
void enqueue(Queue* queue, int item) {
285+
if (isFull(queue))
286+
return;
287+
queue->rear = (queue->rear + 1) % queue->capacity;
288+
queue->data[queue->rear] = item;
289+
queue->size = queue->size + 1;
290+
}
291+
292+
int dequeue(Queue* queue) {
293+
if (isEmpty(queue))
294+
return INT_MIN;
295+
int item = queue->data[queue->front];
296+
queue->front = (queue->front + 1) % queue->capacity;
297+
queue->size = queue->size - 1;
298+
return item;
299+
}
300+
301+
int* minimumCost(int N, int edges[][3], int edgesSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize) {
302+
int* adj[N];
303+
int adjSize[N];
304+
int* c = (int*)malloc(N * sizeof(int));
305+
int* group = (int*)malloc(N * sizeof(int));
306+
int* res = (int*)malloc(queriesSize * sizeof(int));
307+
*returnSize = queriesSize;
308+
309+
for (int i = 0; i < N; i++) {
310+
adj[i] = (int*)malloc(N * sizeof(int));
311+
adjSize[i] = 0;
312+
c[i] = INT_MAX;
313+
group[i] = -1;
314+
}
315+
316+
// Construct adjacency list and update cost array
317+
for (int i = 0; i < edgesSize; i++) {
318+
int u = edges[i][0], v = edges[i][1], k = edges[i][2];
319+
adj[u][adjSize[u]++] = v;
320+
adj[v][adjSize[v]++] = u;
321+
c[u] &= k;
322+
c[v] &= k;
323+
}
324+
325+
// BFS to find connected components and update cost array for each component
326+
Queue* q = createQueue(N);
327+
for (int i = 0; i < N; i++) {
328+
if (group[i] == -1) {
329+
group[i] = i;
330+
enqueue(q, i);
331+
while (!isEmpty(q)) {
332+
int u = dequeue(q);
333+
c[i] &= c[u];
334+
for (int j = 0; j < adjSize[u]; j++) {
335+
int v = adj[u][j];
336+
if (group[v] == -1) {
337+
group[v] = i;
338+
enqueue(q, v);
339+
}
340+
}
341+
}
342+
}
343+
}
344+
345+
// Process queries
346+
for (int i = 0; i < queriesSize; i++) {
347+
int s = queries[i][0], t = queries[i][1];
348+
if (s == t) {
349+
res[i] = 0;
350+
} else {
351+
if (group[s] == group[t]) {
352+
res[i] = c[group[s]];
353+
} else {
354+
res[i] = -1;
355+
}
356+
}
357+
}
358+
359+
return res;
360+
}
361+
```
362+
</TabItem>
363+
364+
</Tabs>
365+
366+
## Complexity
367+
368+
**Time complexity:**
369+
370+
1. Constructing the adjacency list: $O(E)$, where E is the number of edges.
371+
2. BFS traversal: $O(V + E)$, where V is the number of vertices.
372+
3. Processing queries: $O(Q)$, where `Q` is the number of queries.
373+
4. Overall time complexity: $O(V + E + Q)$.
374+
375+
**Space complexity:**
376+
377+
1. Space for the adjacency list: $O(E)$.
378+
2. Space for the cost array c: $O(V)$.
379+
3. Space for the queue and group array during BFS: $O(V)$.
380+
4. Overall space complexity: $O(V + E)$.
381+
382+
4.68 KB
Loading
5.24 KB
Loading

0 commit comments

Comments
 (0)