G-28. Shortest Path in Undirected Graph with Unit Weights

  Рет қаралды 186,261

take U forward

take U forward

Күн бұрын

Пікірлер: 236
@takeUforward
@takeUforward 2 жыл бұрын
Let's continue the habit of commenting “understood” if you got the entire video. Please give it a like too, you don't 😞 Do follow me on Instagram: striver_79
@harshdasila6680
@harshdasila6680 2 жыл бұрын
problem link is not working !
@sanchittripathi1537
@sanchittripathi1537 Жыл бұрын
dfs code: //{ Driver Code Starts // Initial Template for C++ #include using namespace std; // } Driver Code Ends // User function Template for C++ class Solution { public: void dfs(int index,vectoradj[],vector&visited,vector&dis) { visited[index]=1; for(auto i:adj[index]) { if(!visited[i]) { dis[i]=min(dis[i],1+dis[index]); dfs(i,adj,visited,dis); } else if(dis[i]>dis[index]+1) {dis[i]=min(dis[i],1+dis[index]); dfs(i,adj,visited,dis); } } } vector shortestPath(vector& edges, int N,int M, int src){ // code here vectoradj[N];vectorvisited(N,0); for(int i=0;i> n >> m; vector edges; for (int i = 0; i < m; ++i) { vector temp; for(int j=0; j>x; temp.push_back(x); } edges.push_back(temp); } int src; cin >> src; Solution obj; vector res = obj.shortestPath(edges, n, m, src); for (auto x : res){ cout
@sairam3351
@sairam3351 Жыл бұрын
understood
@adarshmv261
@adarshmv261 5 ай бұрын
Can the same logic be used if this was not having unit weights but having random weights?
@namanjainjain7958
@namanjainjain7958 26 күн бұрын
Yes
@GurugubelliAjay
@GurugubelliAjay 10 ай бұрын
The first time we visit the node , it is our shortest distance since bfs takes 1 unit distance at a time (So no need to compute compare distance ) . vector shortestPath(vector& edges, int N,int M, int src){ vectoradj[N]; for(auto it:edges){ int u=it[0]; int v=it[1]; adj[u].push_back(v); adj[v].push_back(u); } vectordist(N,-1); dist[src]=0; queueq; q.push({src,0}); while(!q.empty()){ int node=q.front().first; int d=q.front().second; q.pop(); for(auto it:adj[node]){ if(dist[it]==-1){ dist[it]=d+1; q.push({it,d+1}); } } } return dist; }
@yashlakade179
@yashlakade179 2 ай бұрын
Thanks a lot of these! Just a small change in your code vector shortestPath(vector& edges, int N,int M, int src){ vectoradj[N]; for(auto it:edges){ int u=it[0]; int v=it[1]; adj[u].push_back(v); adj[v].push_back(u); } vectordist(N,-1); dist[src]=0; queueq; q.push(src); while(!q.empty()){ int node=q.front(); q.pop(); for(auto it:adj[node]){ if(dist[it]==-1){ dist[it] = dist[node]+1; q.push(it); } } } return dist; }
@rohanb9512
@rohanb9512 2 жыл бұрын
Updating the distance of the neighboring nodes is more appropriate for weighted graphs. I think for unweighted graphs the first time when we reach the target node, that should be the shortest distance
@rahulprasad3575
@rahulprasad3575 2 жыл бұрын
Great observation bro
@cr7johnChan
@cr7johnChan Жыл бұрын
yes ,do level order traversal with O(N) time complexity
@idontknow8522
@idontknow8522 Жыл бұрын
@@rahulprasad3575 Its not an observation , BFS do level order traversal , If a node is already visited and try to visit again means that we are currently ahead of that level , going backwards always give bigger distance , so never update visited nodes. ,, Also there is no meaning of taking pair in queue structure ,
@sairam3351
@sairam3351 Жыл бұрын
it's enough we just maintain array of whether node is visited or not.
@infinityzero2321
@infinityzero2321 Жыл бұрын
if you think of it in a way then this is kind of an unweighted graph in itslef since the distance between each neighbour is 1 so if you do not consider it, wont matter.
@priyanshusrivastava2145
@priyanshusrivastava2145 Жыл бұрын
just carry a queue and a distance array which is initially marked a s int_max as soon as we comes to a node we will check if 1+dis[node]
@anishkarthik4309
@anishkarthik4309 Жыл бұрын
I was able to solve this, without even seeing your idea or explanation. Because of your excellent teaching, my intuition is improving.
@niteshsaxena1066
@niteshsaxena1066 5 ай бұрын
same here
@visase2036
@visase2036 2 жыл бұрын
Thank you for your immense efforts Striver. Here is one more easier approach inspired from your (01 matrix graph lecture G13) 1. Initialize distance=[-1]*(V) 2. distance[0]=0 // as ''0' is the src node 3. add (0) alone to the "queue" 2. Plain BFS: Take out the node from the queue Update the children's distance from that node : node=q.front() q.pop() for children in adjList[node]: if distance[children]==-1: #Since BFS will give us the sorted shortest distance its jus enough to check if its -1 distance[children]=distance[node]+weight (weight is 1 here) q.append(children) Once the BFS is done return distance if distance [i]==-1, there is no path from src to that node TC:O(V+2E) SC:O(2V)
@MdSarfrazcs
@MdSarfrazcs 2 жыл бұрын
Hey I have first solve my own via this method , I think the weight of edge is 1 so it's work fine If edges weight vary than this approach didn't work in that case we have to follow standard ways that striver teach
@champion5946
@champion5946 Жыл бұрын
@@MdSarfrazcs yes
@rakshan3323
@rakshan3323 5 ай бұрын
@@MdSarfrazcs Yes, It is because the first distance need not be the minimum distance possible.
@MdSarfrazcs
@MdSarfrazcs 5 ай бұрын
@@rakshan3323 lol 🤣 there was time I was solving a graph problem my own now this is the time where I can't solve a medium tree questions feel pitty for my self 😢
@kartikgarg7541
@kartikgarg7541 4 ай бұрын
@@MdSarfrazcs Bro really commented 1 year later
@bmishra98
@bmishra98 Ай бұрын
In the explanation, you had put pairs in queue, but in the code you just pushed the node. I have written the code according to your explanation and it works: vector shortestPath(vector& edges, int N,int M, int src){ vector adj[N]; // creating an adjacency list to store a graph // Build the adjacent node list from the given edges for(int i = 0; i < M; i++) { // M is nothing but no.of edges in graph, i.e., edges.size() int u = edges[i][0]; int v = edges[i][1]; adj[u].push_back(v); adj[v].push_back(u); } queue q; // creating a queue to facilitate BFS traversal vector dist(N, 1e9); // creating a 'dist' array initialized all elements with infinity to keep track of shortest distance q.push({src, 0}); // pushing the source node in queue along with the shortest distance to reach there being 0 obviously dist[src] = 0; // mark dist[src] as 0 while(!q.empty()) { int node = q.front().first; // this is the current node int distance = q.front().second; // this is the shortest distance to reach this current node q.pop(); // Traverse neighbours of the current node and update the 'dist' array and push {node, distance} in queue // if a shorter distance is found to reach the neighbour than the existing distance to reach neighbour. for(int neighbour: adj[node]) { if(distance + 1 < dist[neighbour]) { dist[neighbour] = distance + 1; q.push({neighbour, distance+1}); } } } // If a node is unreachable, mark it as -1. for(int i = 0; i < N; i++) { if(dist[i] == 1e9) dist[i] = -1; } return dist; }
@anubhavbhutani8512
@anubhavbhutani8512 2 ай бұрын
we can apply the same thing we are doing in this question to the previous question i.e Shortest Path in Directed Acyclic Graph as well. This is the code. vector adj[N]; // Adjacency list for weighted graph for (int i = 0; i < M; i++) { int u = edges[i][0], v = edges[i][1], weight = edges[i][2]; adj[u].push_back({v, weight}); } vector dist(N, INT_MAX); queue q; q.push(0); dist[0] = 0; while (!q.empty()) { int node = q.front(); q.pop(); // Explore neighbors for (auto it : adj[node]) { int nextNode = it.first; int edgeWeight = it.second; // Relaxation step if (dist[node] + edgeWeight < dist[nextNode]) { dist[nextNode] = dist[node] + edgeWeight; q.push(nextNode); } } } // Replace unreachable nodes' distances with -1 for (auto &it : dist) { if (it == INT_MAX) it = -1; } return dist; }
@CS090Srikanth
@CS090Srikanth Ай бұрын
This wont work for the previuous question due to dissimilar edge weights it would have worked if dag has edge weights as same (1)... Assume we have adjacency list as 0 --> [{1,4},{2,1}] 1 --> [{3,1}] 2 --> [{1,1},{4,6}] 3 --> [{4,1},{5,4}] 4 --> [{6,2},{7,1}] 5 --> [] 6 --> [{5,1}] 7 --> [] Dry run this to understand
@divyareddy7622
@divyareddy7622 Ай бұрын
its the exact same code for the both the questions right?
@ashdaily7640
@ashdaily7640 23 күн бұрын
why did we use topo sort there then?
@stith_pragya
@stith_pragya 6 ай бұрын
Understood..............Thank You So Much for this wonderful video..........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@abheykalia3409
@abheykalia3409 Жыл бұрын
we can use dist array as a vis[] substitute since those dist[i] which have values !=INF are already visited
@aakashgoswami2356
@aakashgoswami2356 2 жыл бұрын
If anyone curious about how it can be solved using dfs .Here is the code. private: void findShortestPath(vectoradj[],int V,int node,vector&vis,vector&dist){ vis[node] = 1; for(auto adjNode:adj[node]){ if(dist[adjNode]>dist[node]+1) dist[adjNode] = dist[node]+1; if(!vis[adjNode]){ findShortestPath(adj,V,adjNode,vis,dist); } } vis[node] = 0; return; } public: vector shortestPath(vector& edges, int N,int M, int src){ vectoradj[N]; for(auto edge:edges){ int u = edge[0]; int v = edge[1]; adj[u].push_back(v); adj[v].push_back(u); } vectorvis(N,0); vectordist(N,INT_MAX); dist[src] = 0; findShortestPath(adj,N,src,vis,dist); for(int i=0;i
@keertilata20
@keertilata20 Жыл бұрын
thank you so much, you cleared my doubt
@ayushmansharma5321
@ayushmansharma5321 Жыл бұрын
@sumurthdixit8482
@sumurthdixit8482 Жыл бұрын
It can also be solved without using visited array. we only need to do a dfs for a node if it's distance value was minimized in the current dfs call. here is the code void dfs(int s, vector& dist, vector& g) { for(int to : g[s]) { if(dist[to] > dist[s] + 1) { dist[to] = dist[s] + 1; dfs(to, dist, g); } } } vector shortestPath(vector& edges, int N,int M, int src){ vector g(N); for(auto e : edges) { g[e[0]].push_back(e[1]); g[e[1]].push_back(e[0]); } vector dist(N, 1e9); dist[src] = 0; dfs(src, dist, g); for(int & node : dist) { if(node == 1e9) node = -1; } return dist; }
@amitrawat8879
@amitrawat8879 Жыл бұрын
why a single dfs call worked here. and why not the standard dfs where we check if the node is visited then only call the dfs in the main function.
@toontime7663
@toontime7663 Жыл бұрын
@@amitrawat8879 becuz after the first dfs call ,all the nodes that are left would be unreachable through the source node and hence we need not to perform dfs for them and in the end we simply assign them -1.
@Ben10qz
@Ben10qz 2 жыл бұрын
we can use vis array also so that is can skip some as if it reaches again to some other node dist must be greater than previous.
@rishabhranjan5162
@rishabhranjan5162 5 ай бұрын
This approach is best for weighted edges. For shortest distance we can just maintain a visited array and do dfs.
@sahelidebnath5085
@sahelidebnath5085 9 ай бұрын
Your explanation is insightful. I really love your videos. Thanks for all your dedication for this lovely videos. I have a doubt regarding the repeated checking of vertices in this problem. Since there is a unit distance between vertices, if vertex 3 has been reached previously by vertex 0, why should we check it again? It seems redundant as the distance to vertex 3 will only increase over time, given that the weight is fixed at 1. Instead of repeatedly checking the same vertex, I believe it would be more efficient to maintain a visited array. This would allow us to check if a vertex has already been visited before adding it to the queue, reducing the number of queue operations and subsequently improving the time complexity. While this approach may increase the space complexity by O(n), the overall time complexity will be reduced. I am eager to hear your thoughts on this. I am just bringing by concern. public int[] shortestPath(int[][] edges,int n,int m ,int src) { ArrayList adj = new ArrayList(); int[] dist = new int[n]; Arrays.fill(dist,(int)1e9); boolean[] vis = new boolean[n]; Queue q = new LinkedList(); for(int i= 0;i
@Maunil2k
@Maunil2k 5 ай бұрын
I have an alternate solution to this. We maintain a visited array and initialize it to 0 except for the source node which is 1 (just like a typical BFS solution). Now, instead of checking for distance(i.e. is the current distance lesser than the previous distance), we check whether the node has been visited or not. If the node is not visited then we simply update the curr_distance + 1 in the distance array for this particular node and push it to the queue. Intuition: If the node hasn't been previously visited then the distance is infinity hence, without checking we can update the distance to dist. + 1 If the node has been previously visited then there is no need to check for distance as it will definitely greater than the current one. This is because BFS explores all the neighbors of the node before moving on to the next node. Code for the same is written below. ``` class Solution { public: vector shortestPath(vector& edges, int N,int M, int src){ vector adj[N]; for(int i=0; i
@meetverma4812
@meetverma4812 3 ай бұрын
but if we mark the node as visited we cannot visit it again then how can we make the count of minimum distance in the distance array ?
@princegupta451
@princegupta451 2 ай бұрын
@@meetverma4812 since the question states that the edges are unit weighted, we only need to reach every node once. BFS traverses by levels and at every next layer the distance would increase by 1. So if I reached a node with a distance of 2 through BFS, next time whenever i reach that node again, the distance would always be greater than what i previously had for that node. However this would only work for unit weighted graph whereas striver's code would work for all cases.
@saisreeramputta7724
@saisreeramputta7724 Жыл бұрын
class Solution { public: vector shortestPath(vector& edges, int N,int M, int src){ vector adj[N]; vector dis(N,-1); vector vis(N,-1); queue q; for(int i = 0;i
@abrarmojahidrafi4509
@abrarmojahidrafi4509 Жыл бұрын
I think, for Node 3, the adjacency list will be "0, 1, 4"; not "0, 4".
@JaiN-bj1pj
@JaiN-bj1pj Жыл бұрын
You only have to add the node to the queue, during the first instance, when it's distance is not yet computed. If you are adding it every time it gets updated, it is unnecessary.. code below: public int[] shortestPath(int[][] edges,int n,int m ,int src) { // Code here int[] dist = new int[n]; Arrays.fill(dist, -1); int level = 0; Queue q = new LinkedList(); List adj = new ArrayList(); for(int i=0;i
@muditkhanna8164
@muditkhanna8164 Жыл бұрын
the queue will push the already pushed although it would impact the distance array as the condition for minimum exist, but can cause high time complexity.
@cinime
@cinime 2 жыл бұрын
Understood! Such a wonderful explanation as always, thank you very much!!
@itsaryanb9316
@itsaryanb9316 2 жыл бұрын
can anyone share me the link to this question?? the description link isn't working !
@yasaswinikarumuri9590
@yasaswinikarumuri9590 2 жыл бұрын
Is there any significance of pushing pair of {Node,dist} into Queue.I mean, is the dist needed to be pushed?Like we can directly fetch the dist from the dist array right?Please do answer this!
@takeUforward
@takeUforward 2 жыл бұрын
Yes you can! I was doing it for explanation. You can see a note added in the video when I code it. I guess you skipped some portion of video.
@NituPandelPCECS
@NituPandelPCECS Жыл бұрын
@@takeUforward With pair class class pair{ int v, wt; pair(int v, int wt){ this.v = v; this.wt = wt; } } class Solution { public int[] shortestPath(int[][] edges,int n,int m ,int src) { ArrayList adj = new ArrayList(); for(int i = 0; i < n; i++){ adj.add(new ArrayList()); } for(int i = 0 ; i < m; i++){ int a = edges[i][0]; int b = edges[i][1]; adj.get(a).add(b); adj.get(b).add(a); } int dis[] = new int[n]; for(int i = 0 ; i < n; i++){ dis[i] = (int)1e9; } Queue pq = new LinkedList(); pq.add(new pair(src, 0)); dis[src] = 0; while(!pq.isEmpty()){ int first = pq.peek().v; int sec = pq.peek().wt; pq.remove(); for(int it : adj.get(first)){ if(dis[it] > sec+1){ pq.add(new pair(it, sec+1)); dis[it] = sec+1; } } } for(int i = 0 ; i < n; i++){ if(dis[i] == 1e9) dis[i] = -1; } return dis; } }
@RahulYadav-i6f6c
@RahulYadav-i6f6c Жыл бұрын
@takeUforward can't we implement Dijkstra algorithum like this? Why we are creating visited and finding the min distance node using priority queue? Why cant we just use this method?
@apmotivationakashparmar722
@apmotivationakashparmar722 12 күн бұрын
Thank you Striver !
@rakshitsathyakumar4332
@rakshitsathyakumar4332 Жыл бұрын
very similar to level order traversal in binary tree trversal alternative:- class Solution { public: vector shortestPath(vector& edges, int N,int M, int src){ // code here vector adj[N]; for(int i=0;i
@_CodeLifeChronicles_
@_CodeLifeChronicles_ Ай бұрын
i am in the 23 rd q from graph series i hope i will complete till the end
@kaichang8186
@kaichang8186 2 ай бұрын
understood, thanks for the great video
@chiragPatel22c
@chiragPatel22c Жыл бұрын
but striver, to make adjacency list we'll need O(E) space complexity, but gfg has asked for O(N) space complexity.
@AmanSingh-dk4eg
@AmanSingh-dk4eg 2 жыл бұрын
bhaiya transform ho gye 11:24
@abhisheknag1929
@abhisheknag1929 8 ай бұрын
Simple BFS will give answer #include using namespace std; vector shortestPath(int n, vector &graph, int src) { // ADJACENCY LIST vector adj[n]; for(auto edge:graph) { int u = edge[0]; int v = edge[1]; adj[u].push_back(v); adj[v].push_back(u); } // Prepare BFS // unordered_map vis; //no need of visited here answer/distance array also works as visited vector answer(n, -1); // Initialize all distances to -1 // Implement BFS queue q; q.push(src); // vis[src] = true; answer[src] = 0; // Distance to source node is 0 while (!q.empty()) { int front = q.front(); q.pop(); for (auto it : adj[front]) { if (answer[it]==-1) { // vis[it] = true; q.push(it); // Update the distance answer[it] = answer[front] + 1; } } } return answer; }
@rishabhagarwal8049
@rishabhagarwal8049 2 жыл бұрын
Understood sir, Thank you very much
@CodeDaily29
@CodeDaily29 4 ай бұрын
hey striver, Can you tell me when to use stack or queue. Or should I memorize them for every question?
@elites5967
@elites5967 2 жыл бұрын
key observation : This video was recorded over two weekends( explanation on one and coding on the other ).
@Moch117
@Moch117 Жыл бұрын
What is the difference between this and Dijkstras ?
@anhadorigamichannel9800
@anhadorigamichannel9800 5 ай бұрын
why not make a vis array this time it would significantly enhance time complexity
@adarshmv261
@adarshmv261 5 ай бұрын
Can the same logic be used if this was not having unit weights but having random weights?
@DevashishJose
@DevashishJose 9 ай бұрын
understood, Thank you so much.
@amitp277
@amitp277 Жыл бұрын
Great explanation
@praveshjain7525
@praveshjain7525 4 ай бұрын
Hey, which tool do you use for online teaching? Can you please share the details of your setup?
@vikasshokeen6044
@vikasshokeen6044 4 ай бұрын
Why didn't we apply the Topology search here.?
@ritamganguli3476
@ritamganguli3476 2 жыл бұрын
Striver bhiya I am stuck in dp should I do graph after recursion and backtracking also sometimes i forget the approach like the n queen so how to remember them
@parshchoradia9909
@parshchoradia9909 Жыл бұрын
Understood SIr!
@utkarshsingh245
@utkarshsingh245 10 ай бұрын
understandable solution so far Down below void bfstraverse(vector adj[], vector &mindistance, int visited[], int nodes){ queue que; que.push({0, 0}); visited[0] = 1; mindistance[0] = 0; while(!que.empty()){ int node = que.front().first; int weight = que.front().second; que.pop(); for(auto it : adj[node]){ if(visited[it] != 1){ visited[it] = 1; mindistance[it] = min(mindistance[it], weight+1); que.push({it, mindistance[it]}); } } } } vector mindistances(vector adj[], int nodes){ vector mindistance(nodes); fill(mindistance.begin(), mindistance.end(), INT_MAX); int visited[nodes] = {0}; bfstraverse(adj, mindistance, visited, nodes); return mindistance; }
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir 🙏
@googleit2490
@googleit2490 Жыл бұрын
Understood :) Sep'1, 2023 11:53 pm
@itsaryanb9316
@itsaryanb9316 2 жыл бұрын
Thanks alott for your effort bhaiya❤️❤️❤️
@jayantgahlot2653
@jayantgahlot2653 Жыл бұрын
doubt: can't we do previous que with this logic ?
@AyushKumar-ty4cl
@AyushKumar-ty4cl Жыл бұрын
Previous question can also be solve using this method, plain bfs
@imtiyazuddin4827
@imtiyazuddin4827 8 ай бұрын
yes, it can be solved but since in previous question all edges had unequal weights therefore plain bfs would create redundancies as we have to update everytime we get shortest distance
@KratosProton
@KratosProton 2 жыл бұрын
Great explaination
@geen4562
@geen4562 5 ай бұрын
Why no visited array here? what if it had multiple components??
@lakshsinghania
@lakshsinghania Жыл бұрын
was able to get the intuition and coded myself the dfs part without watching the video
@justanuhere
@justanuhere 6 ай бұрын
why cant we solve this question using dijkstra and topo sort like in the previous video?
@chitranshjawere4953
@chitranshjawere4953 5 ай бұрын
Here's the bfs approach : class Solution { public: vector bfstopo(int V, vector adj[]) { // code here queue q; vectorans; vector indeg(V,0); for(int i=0 ; i < V ; i++){ for(auto &adjnode : adj[i])indeg[adjnode.first]++; } for(int i =0 ; i < V; i++){ if (indeg[i]==0)q.push(i); } while(!q.empty()){ auto node =q.front(); ans.push_back(node); q.pop(); for(auto &adjnode :adj[node]){ indeg[adjnode.first]--; if (!indeg[adjnode.first])q.push(adjnode.first); } } return ans; } vector shortestPath(int N,int M, vector& edges){ // code here vector dis(N,1e9); vector adj[N]; for(int i = 0; i< M ; i++){ int a = edges[i][0]; int b = edges[i][1]; int w =edges[i][2]; adj[a].push_back({b,w}); } vector topo = bfstopo(N,adj); //starting point need not mean that it is the starting point of topos // so topos lagana to pura hi padega :) dis[0] = 0; for(int i = 0 ; i < topo.size() ; i++){ int node = topo[i]; if (dis[node] != 1e9) { for (auto &it : adj[node]) { int v = it.first; int wt = it.second; if (dis[node] + wt < dis[v]) { dis[v] = wt + dis[node]; } } } } for(int &i : dis){ if (i==1e9)i=-1; } return dis; } };
@Rieshu-l9i
@Rieshu-l9i 7 ай бұрын
#Striver rocks 🤟👍
@user-rf3he9uv5m
@user-rf3he9uv5m Жыл бұрын
understood striver.
@manishreddy58
@manishreddy58 5 ай бұрын
Why is it not checked for connected components?
@namamiNarayana
@namamiNarayana Жыл бұрын
Understood! :) Thank you for your invaluable efforts striver! _/\_ ^^
@gaurav4270
@gaurav4270 2 жыл бұрын
do we acutally need that dis[u]>dis[v]+1 check condition ,since we are doing bfs in bfs nodes at distance are reched first than nodes at distance 2 and so on .... //here v is the source queueq; q.push(v); visited[v]=true; while(q.empty()==false) { int u=q.front(); q.pop(); for(auto it:adj[u]) { if(visited[it]==false) { res[it]=res[u]+ 1; visited[it]=true; q.push(it); } } } this should do the job ryt?? although it giving wrong answer in gfg...................
@YeaOhYeahh
@YeaOhYeahh 2 жыл бұрын
hmmm, I agree with u there is no need of dis[u]>dis[v]+1. Did u initialize res array with " -1 " ??
@gaurav4270
@gaurav4270 2 жыл бұрын
@@YeaOhYeahh yesss
@shivasai7707
@shivasai7707 Жыл бұрын
did you figure out why did it fail ? I'm stuck at the same
@user-le6ts6ci7h
@user-le6ts6ci7h Жыл бұрын
Initialize all of them to 0 with source to -1
@hope-jh7bv
@hope-jh7bv 6 ай бұрын
Understood sir.
@The_Shubham_Soni
@The_Shubham_Soni Жыл бұрын
Here is the DFS approach for the same 👇✅ private: void dfs(int node, int vis[], vector &dist, vector adj[]) { vis[node]=1; for(auto i: adj[node]) { if(dist[node]+1 < dist[i]) { dist[i]=dist[node]+1; dfs(i, vis, dist, adj); } } } public: vector shortestPath(vector& edges, int N,int M, int src){ // code here // adjacency list vector adj[N]; for(auto i: edges) { int u=i[0]; int v=i[1]; adj[u].push_back(v); adj[v].push_back(u); } // dfs karo int vis[N]={0}; vector dist(N, 1e9); dist[src]=0; for(int i=0;i
@rahulmehndiratta3856
@rahulmehndiratta3856 Жыл бұрын
You dont need to perform dfs on all unvisited vertices. Only perform dfs on root to cover all the vertices reachable from root Rest all will be -1 off course
@anuragprasad6116
@anuragprasad6116 10 ай бұрын
same path is being iterated multiple times. it'll give TLE on large test cases
@rishabhnema2479
@rishabhnema2479 4 ай бұрын
Shouldn't we store the distance of the adjacent nodes as pairs and then update the distance? Here is my GFG code: class Solution { public: vector shortestPath(vector& edges, int N,int M, int src){ // code here vectoradj(N); for(int i = 0;iwt+1){ dist[it] = wt+1; q.push({it,dist[it]}); } } } for(int i = 0;i
@Learnprogramming-q7f
@Learnprogramming-q7f 6 ай бұрын
Thank you bhaiya
@Swiftie13498
@Swiftie13498 9 ай бұрын
Understood Bhaiya
@bhaktisharma9681
@bhaktisharma9681 7 ай бұрын
Why dont we push node and distance both in the queue as it being done in the explanation, but not while writing code?
@SakshiSingh-hv1oo
@SakshiSingh-hv1oo 5 ай бұрын
same doubt
@swaraj.nalawade.4634
@swaraj.nalawade.4634 2 ай бұрын
class Solution { public: vector shortestPath(vector& edges, int N,int M, int src){ vector adj[N]; // no need to consider wt as its 1 for(int i=0; i
@googleit2490
@googleit2490 Жыл бұрын
Revision I: Easy peasy Sep'6, 2023 10:46 pm
@ganeshmula4508
@ganeshmula4508 11 ай бұрын
understood sir🙇‍♂🙇‍♂🙇‍♂
@-VLaharika
@-VLaharika Жыл бұрын
Understood 👍
@gautamsaxena4647
@gautamsaxena4647 6 ай бұрын
understood bhaiya
@banothutharun2743
@banothutharun2743 4 ай бұрын
understood bro
@flying_humans
@flying_humans 2 жыл бұрын
I think adjacency list is wrong because the adjacent elements of 3 are 0,1,4 but you have only written 0 and 4.
@takeUforward
@takeUforward 2 жыл бұрын
Okay okay, you understood na 😅 typos happen!
@keertilata20
@keertilata20 2 жыл бұрын
you are greattttttt😃
@valarmorghulis9244
@valarmorghulis9244 Жыл бұрын
Is the queue of pairs needed? like cant we have only nodes inside the queue and get the distance of that node from dist array?
@saumyaagarwal7
@saumyaagarwal7 Жыл бұрын
see his code properly
@p_s1dharth
@p_s1dharth 5 ай бұрын
understood sir
@tanishkumar6682
@tanishkumar6682 Жыл бұрын
UNDERSTOOD
@suryakiran2970
@suryakiran2970 Жыл бұрын
Understood❤
@lokeshnaidu9324
@lokeshnaidu9324 5 ай бұрын
How is it different from dijsktras algorithms as it also involves relaxation
@akshatgosain3831
@akshatgosain3831 Жыл бұрын
efficient c++ code: vector adj(n); for(int i=0;i
@pranavindore2410
@pranavindore2410 8 ай бұрын
understood 😀
@josephstark5810
@josephstark5810 Жыл бұрын
simple level order traversal
@10ankurpandey54
@10ankurpandey54 Жыл бұрын
love u bro
@KapilSharma56419
@KapilSharma56419 4 ай бұрын
anyone tell can we apply this method to DAG if no then why and if yes then comment the code in reply?
@anubhavjasoria4335
@anubhavjasoria4335 2 жыл бұрын
i tried the given problem using dfs and getting very little difference in the output please can someone help me figure this out void dfs(vector&vis,int i,vectoradj[],vector&dis,int d,int par){ vis[i]=1; dis[i]=min(dis[i],d); // cout
@saseerak8763
@saseerak8763 2 жыл бұрын
public int[] shortestPath(int[][] edges,int n,int m ,int src) { // Code here ArrayList adj = new ArrayList(); for(int i=0;i
@juniorboy1903
@juniorboy1903 2 жыл бұрын
Bhaiya it is recommended that can i watch your old graph video or not
@aryashjain7893
@aryashjain7893 2 жыл бұрын
Sari dekhlo , bahut acchi hai sab🙂
@altafmazhar7762
@altafmazhar7762 2 жыл бұрын
No it is not necessary
@tanujgarg20
@tanujgarg20 Жыл бұрын
Wont there be same problem be occuring here as discussed in comment section of previous question i.e there will be too many redundancies in this when using BFS method. Wont it be better if this problem is also solved using toposort and then relax the edges.?
@ababhimanyu806
@ababhimanyu806 Жыл бұрын
toposort is for directed graph(DAG) here its undirected
@paracetamol9116
@paracetamol9116 7 ай бұрын
@@ababhimanyu806 doesn't matter, can assume weights to be 1 and apply it. We can't apply it cuz it works for acyclic graphs only.
@pavansrinivas4388
@pavansrinivas4388 3 ай бұрын
Does the same not work for DAG with non unit weights?
@pavansrinivas4388
@pavansrinivas4388 3 ай бұрын
Realized it wont work
@StoriesFromWeb13
@StoriesFromWeb13 21 күн бұрын
thank u nice
@suhaanbhandary4009
@suhaanbhandary4009 Жыл бұрын
understood!!
@p38_amankuldeep75
@p38_amankuldeep75 2 жыл бұрын
understood❤❤❤❤❤
@harleenkaur7751
@harleenkaur7751 Жыл бұрын
understood😊
@saksham-arora
@saksham-arora 2 ай бұрын
Basic level order should work @takeUForward vector shortestPath(vector& edges, int N,int M, int src){ vector level(N, -1); vector ad(N); for(auto x: edges) { ad[x[0]].push_back(x[1]); ad[x[1]].push_back(x[0]); } queue q; q.push(src); level[src] = 0; while(!q.empty()) { int t = q.front(); q.pop(); for(auto x:ad[t]) { if(level[x] == -1) { level[x] = level[t] + 1; q.push(x); } } } return level; }
@aniketchaudhary5803
@aniketchaudhary5803 2 жыл бұрын
Understood!!!!
@technologicalvivek7510
@technologicalvivek7510 4 ай бұрын
priority queue kyu nhi use hui isme bhaiya?
@moviesflix7082
@moviesflix7082 3 ай бұрын
EASY JAVA CODE: class Pair{ int node; int dist; Pair(int node, int dist){ this.node=node; this.dist=dist; } } class Solution { public int[] shortestPath(int[][] edges,int n,int m ,int src) { ArrayList adj = new ArrayList(); for(int i=0; i
@Abhi-zr1pb
@Abhi-zr1pb 3 ай бұрын
why this dfs giving me a tle at test case 1055 on gfg? //{ Driver Code Starts import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { int n = sc.nextInt(); int m=sc.nextInt(); int[][] edge = new int[m][2]; for(int i=0;i
@shivamsethia2967
@shivamsethia2967 Жыл бұрын
thanks :)
@supratimnayek2776
@supratimnayek2776 2 жыл бұрын
Understood
@hareeshr3979
@hareeshr3979 2 жыл бұрын
Hey strivver I can't find the problem link , I tried googling and still can't find it , The one you provided in desc is not working same for the previous video
@ashishbisht5359
@ashishbisht5359 2 жыл бұрын
here you go -> practice.geeksforgeeks.org/problems/shortest-path-in-undirected-graph-having-unit-distance/1?page=1&sortBy=accuracy&query=page1sortByaccuracy
@sayakghosh5104
@sayakghosh5104 2 жыл бұрын
practice.geeksforgeeks.org/problems/shortest-path-in-undirected-graph-having-unit-distance/1?page=1&sortBy=accuracy&query=page1sortByaccuracy
@durgeshjadhav01
@durgeshjadhav01 4 ай бұрын
nice
@harshdasila6680
@harshdasila6680 2 жыл бұрын
understoooodooddddd
@sanamdeepsingh7914
@sanamdeepsingh7914 2 жыл бұрын
understood
G-29. Word Ladder - I | Shortest Paths
28:07
take U forward
Рет қаралды 217 М.
Twin Telepathy Challenge!
00:23
Stokes Twins
Рет қаралды 98 МЛН
МЕНЯ УКУСИЛ ПАУК #shorts
00:23
Паша Осадчий
Рет қаралды 5 МЛН
6.8 Cycle detection in Directed Graph |Data Structures and Algorithms Tutorials
10:36
G-27. Shortest Path in Directed Acyclic Graph - Topological Sort
26:36
take U forward
Рет қаралды 241 М.
G-11. Detect a Cycle in an Undirected Graph using BFS | C++ | Java
20:19
G-35. Print Shortest Path - Dijkstra's Algorithm
19:20
take U forward
Рет қаралды 218 М.
Breadth First Search grid shortest path | Graph Theory
16:51
WilliamFiset
Рет қаралды 338 М.
Twin Telepathy Challenge!
00:23
Stokes Twins
Рет қаралды 98 МЛН