No video

G-7. Number of Provinces | C++ | Java | Connected Components

  Рет қаралды 274,852

take U forward

take U forward

Күн бұрын

GfG-Problem Link: bit.ly/3yR3dIB
C++/Java/Codes and Notes Link: takeuforward.o...
DP Series: • Striver's Dynamic Prog...
SDE Sheet: takeuforward.o...
Check out our Website for curated resources:
Our Second Channel: / @striver_79
In case you are thinking to buy courses, please check below:
Code "takeuforward" for 15% off at GFG: practice.geeks...
Code "takeuforward" for 20% off on sys-design: get.interviewr...?_aff=takeuforward
Crypto, I use the Wazirx app: wazirx.com/inv...
Take 750 rs free Amazon Stock from me: indmoney.oneli...
Earn 100 rs by making a Grow Account for investing: app.groww.in/v...
Linkedin/Instagram/Telegram: linktr.ee/take...
---------------------------------------------------------------------------------------------------------------------------

Пікірлер: 341
@takeUforward
@takeUforward 2 жыл бұрын
Let's continue the habit of commenting “understood” if you got the entire video. Do follow me on Instagram: striver_79
@shubhamshukla4215
@shubhamshukla4215 2 жыл бұрын
Hey Striver, I am just wondering is there any need adding adjLs[i].push_back(j); adjLs[j].push_back(i); I think adjLs[i].push_back(j) will get the job done, because adj Matrix will store the information whether it's two way connection or one way.
@kunalbandooni4009
@kunalbandooni4009 2 жыл бұрын
Striver: Hey Everyone.. Me: *likes the video* Context: Belief in the content I am going to learn. Learning a lot!!
@alt-f4gaming222
@alt-f4gaming222 Жыл бұрын
why are we writing the dfs code in the private, can anyone pls explain the difference in writing the function in private and public
@apexgamer1288
@apexgamer1288 Жыл бұрын
​@@shubhamshukla4215a😊😊
@AnkitGupta-tp3ln
@AnkitGupta-tp3ln Жыл бұрын
I really like the Neon red light of your pen, and how it stays for few seconds before it goes away so that it don't clutter. That's so amazing.
@yashrawat5158
@yashrawat5158 Жыл бұрын
its a glitter feature in an app. which stays for few seconds and then disappears .
@divyanksharma236
@divyanksharma236 Жыл бұрын
naye naye lagte ho
@srirambharadwaj1937
@srirambharadwaj1937 8 ай бұрын
It’s on goodnotes for ipad.
@satendra6200
@satendra6200 7 ай бұрын
😅@@divyanksharma236
@rishabhranjan5162
@rishabhranjan5162 3 ай бұрын
It's a Goodnotes 5 feature on ipad
@user-ti3bd8mp1w
@user-ti3bd8mp1w Жыл бұрын
In the code to convert adjacency matrix to adjacency list: striver mentioned 2 lines : adj[i].push_back(j); //1 adj[j].push_back(i); //2 I think it should only have first otherwise there would be repetitions...it works in code bcz visited handles repetitions
@alexwhitewood6480
@alexwhitewood6480 Жыл бұрын
This only works bcz we're going through all the nodes in the outer loop anyways
@srijangupta4680
@srijangupta4680 Жыл бұрын
seen this comment after wasting my whole day🥺
@xyz1869
@xyz1869 11 ай бұрын
correct 👍👍
@tsk1217
@tsk1217 10 ай бұрын
You are right
@toobasedfortheworld
@toobasedfortheworld 10 ай бұрын
Hey why it is given i!=j in convertion of matrix to list?
@Sachinraj_143-king
@Sachinraj_143-king 2 ай бұрын
No i think time complexity of this question is O(n^2). because one loop is travel for all vertices and in each one loop a inner loop is also created .here not O(n)+O(v+2E) .I think here T.C. is O(n)*O(v+2e) which is approximately equal to O(n^2)
@vaibhavthalanki7320
@vaibhavthalanki7320 Ай бұрын
no
@kapilsingh2816
@kapilsingh2816 Жыл бұрын
4:39 the loop is for (int i = 1; i
@sooyashjaju4208
@sooyashjaju4208 Жыл бұрын
Actually kapil, the diagram Given is based on 1 indexing but the solution which it is accepting is 0 based, I faced same issue and eventually made 5 wrong submission 😄
@tusharvlogs6333
@tusharvlogs6333 Жыл бұрын
@@sooyashjaju4208 bhaiiii gladd i came here to see this comment. wasted my 1 hr . thankyou for answering this
@VishalPatel_imvishal
@VishalPatel_imvishal Жыл бұрын
+1 underrated comment
@Virtualexist
@Virtualexist 5 ай бұрын
@@sooyashjaju4208Thanks man! I wasted a lot of time thinking about it. Diagram and test cases should be in sync. 😢 But yea thanks!!!
@Virtualexist
@Virtualexist 5 ай бұрын
Thanks for asking!
@kausachan4167
@kausachan4167 Жыл бұрын
nice explanation striver bhai, one doubt is that should we need to do adj[i].push(j) and adj[j].push(i) both? I think one is enough bcoz anyway we're traversing the matrix completely and it is an undirected graph so edge will be marked in both matrix[i][j] and matrix[j][i], if we push it twice we will have duplicate elements in array list which is not a problem but still can be avoided. crct me if im wrong.
@100anvay5
@100anvay5 Жыл бұрын
i am also thinking about this. yes it will work
@NARENDRAPAL-zh6fk
@NARENDRAPAL-zh6fk Жыл бұрын
Yes, it will work
@varunaggarwal7126
@varunaggarwal7126 Жыл бұрын
nice catch
@AbhishekVerma-yw1ps
@AbhishekVerma-yw1ps Жыл бұрын
Rudrashish
@yoshitaratnawat8425
@yoshitaratnawat8425 Жыл бұрын
In adjacency list representation of unordered graph we need to update the edge for both the vertices that's why we've pushed both
@startercoder
@startercoder 8 ай бұрын
really impressive content , even now I am tired but your confidence give me confidence to learn
@abdalla4425
@abdalla4425 7 ай бұрын
Perfect. Solved it with martix intially but found it easier to solve after converting adjacency list
@vatsaljain662
@vatsaljain662 Ай бұрын
bhaiya that O(N) should be O(V) basically coz v is total number of vertices and O(N) is what we used to use previously (in arrays , linked list , trees and else where ) , right ??
@RAHULMAHESHWARIdexter
@RAHULMAHESHWARIdexter Ай бұрын
My Approach using BFS (same time complexity) Intuition is that everytime our queue gets empty, we have traversed all connected component to that node. Solved it before watching the video, thought about using dfs also, solved it and watched the video and I am happy that I was able to think exact same dfs solution. class Solution { public: int findCircleNum(vector& isConnected) { int provinces = 0; queue q; int n = isConnected.size(); vector vis(n,0); for(int i=0;i
@tejasc7409
@tejasc7409 2 жыл бұрын
Bhaiya ! You can add a node to adjacency list only once . adj.get(i).add(j) is enough , not vice versa . It runs fine
@sushyyyyyyyy
@sushyyyyyyyy 2 жыл бұрын
only once is for directed graphs & vice-versa is for undirected!
@tejasc7409
@tejasc7409 2 жыл бұрын
@@sushyyyyyyyy not in this case. As it has been given in Adjacency matrix. So it will be one if there is an edge.
@sushyyyyyyyy
@sushyyyyyyyy 2 жыл бұрын
@@tejasc7409 no the graph is given undirected! Means two edges from u-> v & v->u like a[u][v] & a[v][u]
@chiragpassi1832
@chiragpassi1832 2 жыл бұрын
@@sushyyyyyyyy yeah , but in matrix for i-j and j-i both have 1 , so it will added anyone
@tejasc7409
@tejasc7409 2 жыл бұрын
@@chiragpassi1832 exactly
@ramanpareek5218
@ramanpareek5218 Ай бұрын
liked the video, notes taken, understood
@anubhavpabby6856
@anubhavpabby6856 2 жыл бұрын
Hi striver bhaiya instead of converting adjList to adjMatrix we could also perform dfs directly on adjMatrix and get the answer. Because it could help us to reduce the space complexity. Code for dfs on adjMatrix : void dfs(int src, vector& adj, vector& visited) { visited[src] = true; for(int i=0; i
@adityajasood4891
@adityajasood4891 Жыл бұрын
Yes , I want to ask leetcode and gfg practice both are same right? Input is adj matrix. Only difference in gfg ArrayList and in leetcode int[][] .
@ajaysarkate6624
@ajaysarkate6624 Жыл бұрын
@@adityajasood4891 In java code, there is already a list given, then we are taking new list in our code?
@jitinroy2246
@jitinroy2246 Жыл бұрын
@@ajaysarkate6624 already given list consist of matrix, so we are converting that from matrix to value type arraylist.
@musaveermanekia4035
@musaveermanekia4035 Жыл бұрын
What's wrong here it shows time limit exceeded at some point void callDfs(vector&vis, vectoradj, int ind){ vis[ind] = true; for(int j = 0; j < adj[ind].size() ; j++){ if(adj[ind][j] == 1 && vis[j] == false){ callDfs(vis, adj, j); } } } int numProvinces(vector adj, int V) { vectorvis(V, false); int ans = 0; for(int i = 0; i < V; i++){ if(vis[i] == false){ callDfs(vis, adj, i); ans++; } } return ans;
@zebra-er6xc
@zebra-er6xc Жыл бұрын
can someone explain if the graph in question is 1 based why don't we run the for loop from 1 to V instead of 0 to V-1
@lavanyam3224
@lavanyam3224 Жыл бұрын
I've solved it myself after watching your previous lecture on dfs. Thanks a lot striver for building my confidence.. I always thought graphs are tough and never imagined that I would be able to solve it myself!! Thanks again striver, you're gold
@ombraforza5780
@ombraforza5780 Жыл бұрын
For anyone who wishes to use the adjacency matrix, here is my code for it. void solve(int node, vector& adj, vector& visited) { visited[node] = true; for (size_t it{0}; it < adj[node].size(); ++it) { if (!visited[it] && adj[node][it]) { solve(it, adj, visited); } } } int numProvinces(vector adj, int V) { vector visited(V, false); int numProvince{0}; for(int node{0}; node < V; ++node) { if(!visited[node]) { ++numProvince; solve(node, adj, visited); } } return numProvince; }
@user-xy5ln4zh5w
@user-xy5ln4zh5w 7 ай бұрын
thanks for sharing
@peddikarthik7832
@peddikarthik7832 Жыл бұрын
when you are converting given matrix to adjacency matrix , no need to run the inner j loop from zero , you can start from j=i+1 , because the lower indexes are already taken care by the 2 lines inside the loops.
@VikashKumar-uz4td
@VikashKumar-uz4td 7 ай бұрын
either u can just pushback j on every i , for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == 1) { adjacencyList[i].push_back(j); } } } it will give correct adjacency list but will repeat in undirected graph , to not repeat it , just pushback in List till n/2(even) or n+1/2 ( if odd). List will be something like this [ [0,2] , [1] , [0,2] ] in undirected graph , and if run list pushback till n+1/2 then [ [0,2] , [1] ] (caution : only do n+1/2 trick on undirected graph , for directed loop till n)
@ishitaamod5109
@ishitaamod5109 Жыл бұрын
How we came to know that it's an adj matrix not list? because in the earlier questions as well it was of the type ArrayList adj ?
@ShivamTh405
@ShivamTh405 Жыл бұрын
It is mentioned in the question or if it is not you can see the sample test cases, if the input consists of only 1s and 0s, it indicates that adjacency matrix is being used
@amantripathi4100
@amantripathi4100 Жыл бұрын
u nailed it bhai
@arnabdebnath2425
@arnabdebnath2425 2 жыл бұрын
Bhaiya your godly explaination of dfs made me do this by my own
@harshitsahu845
@harshitsahu845 Жыл бұрын
9:18 we dont need adjLs[j].push_back(i) as the nodes will be added twice since the matrix caluclates all the possibilites already
@_rmnsingh
@_rmnsingh Жыл бұрын
right
@AkshitSharma0
@AkshitSharma0 Жыл бұрын
Exactly
@user-el6hv6em7m
@user-el6hv6em7m Ай бұрын
understood... Thanks for this amazing series
@cinime
@cinime 2 жыл бұрын
Understood! Awesome explanation as always, thank you very much!!
@kavyabanka4482
@kavyabanka4482 Жыл бұрын
We cannot go from 1-3 how can it is province.
@saieswarimaddula7012
@saieswarimaddula7012 2 ай бұрын
thank you again striver for this wonderful series!! Am able to solve before seeing the solution itself..and all thanks to your excellent explanation:)
@kaichang8186
@kaichang8186 10 күн бұрын
understood, great explanation
@hashcodez757
@hashcodez757 24 күн бұрын
"UNDERSTOOD BHAIYA!!"
@KratosProton
@KratosProton 2 жыл бұрын
Great video, just one suggestion Striver sir, can you please add java code snap in white background as it is very difficult to read in dark background in mobile.
@takeUforward
@takeUforward 2 жыл бұрын
Sure will do that from the next set of videos, thanks for the suggestion
@jitinroy2246
@jitinroy2246 Жыл бұрын
most underrated comment, for the same thing gonna message him on linkedin/instagram. for the black background we have to increase video quality from 480p to 720p then black board java code can be seen properly. so it's not good for the mobile data user's who have limited data/day.
@ayushigupta8633
@ayushigupta8633 Жыл бұрын
I solved this problem without seeing your code, only with the amazing explanation
@ayushidalal5488
@ayushidalal5488 Жыл бұрын
In case anyone is looking for 1-based indexing code: class Solution { void dfs(int node, vector &vis, vector adj[]) { vis[node] = 1; for(auto i: adj[node]) { if(vis[i] == 0) { dfs(i, vis, adj); } } } public: int findCircleNum(vector& isConnected) { // same as no.of components in disconnected graph int n = isConnected.size(); vector adj[n+1]; // convert adjacency matrix into list for(int i=0; i
@aarnasinghal5057
@aarnasinghal5057 Жыл бұрын
thanks and how do we know that in matrix 0 based indexing is being followed and not 1 based indexing? plzz tell
@krishnarajput4125
@krishnarajput4125 2 жыл бұрын
//alternate solution class Solution { public: void dfs(int i,int v,vector adj,vector&vis){ vis[i]=1; for(int it=0;it
@shaikfahim1232
@shaikfahim1232 Жыл бұрын
Thanks bhayya
@RahulKumar-qy7pz
@RahulKumar-qy7pz 13 күн бұрын
i did it myself .....ywahhhhhhhhhhh feeling so happy woooeeeeeeeewwwwww
@himanshukaushik9223
@himanshukaushik9223 4 ай бұрын
Visited array show error variable size object may not initialise but it is working on gfg why anyone reply??
@hah314
@hah314 Жыл бұрын
Thanks Raj, nice explanation, It helped me a lot to solve it by myself.
@jagansubramanian5234
@jagansubramanian5234 Жыл бұрын
Understood. Keep up the good work. May god bless you ❤
@vikasbagri1225
@vikasbagri1225 2 жыл бұрын
understood it very well... thanks for this revised series
@taashukumar1155
@taashukumar1155 Жыл бұрын
matrix +dfs approach:- void dfs(int node,vector adj,int v,vector &vis){ vis[node]=1; for(int i=0;i
@TON-108
@TON-108 5 ай бұрын
Thanks!
@cse048harshkumawat6
@cse048harshkumawat6 2 жыл бұрын
Bhaiya why you can't say it's same as number of components of a graph 😅
@jonny._.1313
@jonny._.1313 2 жыл бұрын
Same question
@RaviKumar-mu4ne
@RaviKumar-mu4ne Жыл бұрын
Because its written there....no. of provinces
@vakhariyajay2224
@vakhariyajay2224 Жыл бұрын
Thank you very much. You are a genius.
@tasneemayham974
@tasneemayham974 8 ай бұрын
HE'S THE BESTTT AND HEE KNOWWS ITT!!!!!!!! UNDERSTOOD STRIVERR!!
@hp2805
@hp2805 Ай бұрын
Thanks so much thalaiva !
@AyushEditz-hs6pf
@AyushEditz-hs6pf 29 күн бұрын
If we are using 1 based indexing, then why are we not making the visited array of length V+1 and not not iterating into it by the condition for( int i=1 ; " i
@harshitgupta5718
@harshitgupta5718 3 ай бұрын
I think instead of converting the adjacency matrix to adjacency list also we can solve it and found it pretty easy to implement. Here is my code for the numProvinces function. I have implemented it using python programming language. def numProvinces(self, adj, V): # code here visited = [False] * V def dfs(node): visited[node] = True for i in range(V): if adj[node][i] == 1 and not visited[i]: dfs(i) count = 0 for i in range(V): if not visited[i]: dfs(i) count += 1 return count
@ayushkumartiwari2684
@ayushkumartiwari2684 2 жыл бұрын
I just have a doubt . Why are we not considering the time complexity to calculate the adjacency list {O(n*n)} ??? Also great content . Waiting for full series to drop.
@rohit2571
@rohit2571 2 жыл бұрын
Good observation.
@chitranjansingh8432
@chitranjansingh8432 2 жыл бұрын
watch from 11:58 again.
@sumerrawat6947
@sumerrawat6947 2 жыл бұрын
time comp n^2 hi hai bhai
@ai-lian7572
@ai-lian7572 2 жыл бұрын
SIR in j=0 to j
@stith_pragya
@stith_pragya 9 ай бұрын
Thank You So Much for this wonderful video......🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@chitranshjain5075
@chitranshjain5075 2 жыл бұрын
Completely UNDERSTOOD.
@jambajuice07
@jambajuice07 Жыл бұрын
solving problem aagain , i am sooo confident in graphhhh now i dont even need to play the video
@rahulsinghshekhawat2487
@rahulsinghshekhawat2487 Жыл бұрын
This is gold.
@universalcosmologist3675
@universalcosmologist3675 2 ай бұрын
thank you very much
@RohitKumar-dz8dh
@RohitKumar-dz8dh Ай бұрын
Understood 😊
@swarupyeole4984
@swarupyeole4984 Жыл бұрын
From Today I started my Graph Playlist again.
@fine2981
@fine2981 Жыл бұрын
how is going?
@vedant6460
@vedant6460 6 күн бұрын
understood
@imnischaygowda
@imnischaygowda Жыл бұрын
Understood, thank you for the playlist.
@kumpatisupriya3947
@kumpatisupriya3947 9 ай бұрын
As usual great explanation......👏👏👏
@ankurmanna2322
@ankurmanna2322 Жыл бұрын
understood and done by myself mostly
@Black_Hat_Chiggy
@Black_Hat_Chiggy Жыл бұрын
"understood"
@herculean6748
@herculean6748 Жыл бұрын
I could solve by myself, thanks striver!
@dreamyme543
@dreamyme543 Жыл бұрын
Understood:)
@anuragC819
@anuragC819 2 жыл бұрын
also is there any approx timeline for remaining videos? eagerly waiting for the full series to drop!
@sumerrawat6947
@sumerrawat6947 2 жыл бұрын
I didn't quite get the time complexity part According to me Let' say we have 4 connected components For component 1 the time complexity for traversal is O(V1+2E1) , where V1, E1 is the number of Nodes and edges of that component 1 For component 2 the time complexity for traversal is O(V2+2E2) , where V2,E2 is the number of Nodes and edges of that component 2 For component 3 the time complexity for traversal is O(V3+2E3) , where V3,E3 is the number of Nodes and edges of that component 3 For component 4 the time complexity for traversal is O(V4+2E4) , where V4 ,E4 is the number of Nodes edges of that component 4 So total time complexity = Sum of time complexity of each component O(V1+2E1) + O(V2+2E2) + O(V3+2E3) + O(V3+2E4) = O(V1+V2+V3+V4) + O(2E1+2E2+2E3+2E4) = O(N) + O(2E) //where N is total nodes in complete graph and E is the total edges in whole graph the total time complexity becomes -> *O(N+2E)* //which is the time complexity to traverse in the whole graph
@takeUforward
@takeUforward 2 жыл бұрын
but you are missing the inner for loop which runs for every traversal.
@sumerrawat6947
@sumerrawat6947 2 жыл бұрын
@@takeUforward bhaiya we are also converting the adj matrix to adj list , for which we traverse the complete matrix , and then we are doing operations with that adj list So actually the time complexity will be O(N^2) 😅 The time complexity will be in the order of N only if we are given the adjacency list directly in the question
@nsudhir_here
@nsudhir_here Жыл бұрын
@@sumerrawat6947 he assumes that Adjacency list is given instead of Adjacency Matric so he doesn't calculate the time complexity for creating Adjacency list from Adjacency Matrix.
@amansinghal4663
@amansinghal4663 Жыл бұрын
I also have the same doubt, if you have understood the time complexity part then can you plz explain it to me ? According to me, the time complexity will be O(N+2E) if we ignore the nested for loops for converting matrix into list.
@pratham654
@pratham654 2 жыл бұрын
Understood very well.
@sripriyapotnuru5839
@sripriyapotnuru5839 Жыл бұрын
Thank you, Striver 🙂
@LearnerForever123
@LearnerForever123 Жыл бұрын
Understood
@444yoshitha8
@444yoshitha8 2 ай бұрын
I solved the question immediatedly after he said we need to change the given input into adjacency list in less than 1min😝
@Sillysmiles76
@Sillysmiles76 Жыл бұрын
Thank you, Understood
@Shivi32590
@Shivi32590 Ай бұрын
thankyou
@rishabhagarwal8049
@rishabhagarwal8049 Жыл бұрын
Understood Sir, Thank you very much
@pixelsbyme
@pixelsbyme 2 жыл бұрын
Understood 🔥, thank you for such videos
@komalkrishna7836
@komalkrishna7836 Жыл бұрын
Understood! nice explanation
@jatilyadav4000
@jatilyadav4000 Жыл бұрын
Amazing as Always...
@p38_amankuldeep75
@p38_amankuldeep75 Жыл бұрын
Enjoyed very much💙💙💙
@GhostRider....
@GhostRider.... Жыл бұрын
Nice Explanation Bhaiya
@suyashapokharna873
@suyashapokharna873 10 ай бұрын
understood striver bhaiya
@abhijitroy1958
@abhijitroy1958 2 жыл бұрын
great explanation of tc
@dilsedhoni9229
@dilsedhoni9229 Жыл бұрын
Understood Striver! Thanks ;-)
@Fuzail_Ahammed
@Fuzail_Ahammed Жыл бұрын
Very nice explanation ✨
@suheabkhan2546
@suheabkhan2546 2 жыл бұрын
understood very very well
@shaikazam5559
@shaikazam5559 9 ай бұрын
Not subscribing and liking is very injustice to strivers talent and hard work we can atleast do this for our gem
@tasneemayham974
@tasneemayham974 8 ай бұрын
Every time Striver says to subscribe, I go down to subscribe and find I am already subscribed!!
@dank7044
@dank7044 3 ай бұрын
did this on my own
@rishabhgupta9846
@rishabhgupta9846 Жыл бұрын
great explanation
@morganyu3391
@morganyu3391 2 жыл бұрын
Understood bhaiya!!
@user-tk2vg5jt3l
@user-tk2vg5jt3l 4 ай бұрын
Thank you bhaiya
@garvitkhandelwal1860
@garvitkhandelwal1860 4 ай бұрын
bro is TUF working ?
@aditya_raj7827
@aditya_raj7827 8 ай бұрын
Love you striver ❤
@vishnu9134
@vishnu9134 7 ай бұрын
Understood ❤
@harshvardhansingh2272
@harshvardhansingh2272 2 жыл бұрын
understood striver
@_hulk748
@_hulk748 Жыл бұрын
understood sir🙇‍♂🙏❤
@shubhigupta5689
@shubhigupta5689 Жыл бұрын
Understood🌻
@girlneedsnoname9488
@girlneedsnoname9488 Жыл бұрын
what is the difference between finding # of islands and finding # of provinces ? is it just the way graph is represented ?
@imyasharya
@imyasharya 3 ай бұрын
understood!
@RitikKumar-bk6pj
@RitikKumar-bk6pj 2 жыл бұрын
Sir yes wale series jada best hai phle ke comparison mai problems ka intuition kafe clear hua isse
@lakeshkumar8239
@lakeshkumar8239 Жыл бұрын
understood sir
@arvindg553
@arvindg553 Жыл бұрын
This is gold
@mriduljain1981
@mriduljain1981 Жыл бұрын
understood.
@rajsekhardutta8891
@rajsekhardutta8891 Жыл бұрын
Understood!🤩
@VikashKumar-uz4td
@VikashKumar-uz4td 7 ай бұрын
looks confusing , adjacency list is printing wrong, here is my version for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (adj[i][j] == 1) { adjacencyList[i].push_back(j); } } } List will be something like this [ [0,2] , [1] , [0,2] ] in undirected graph , and if u will run list.push_back till n+1/2 then [ [0,2] , [1] ] (caution : only do n+1/2 trick on undirected graph , for directed loop till n)
@ISHARAMTEKE-ku2ll
@ISHARAMTEKE-ku2ll 5 ай бұрын
code using BFS traversal : using the list approch i.e creating another adjacency list. int findNumOfProvinces(vector& roads, int n) { vector adjls(n); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(roads[i][j] == 1 && i != j) { adjls[i].push_back(j); adjls[j].push_back(i); } } } vector vis(n, 0); // Initialize all values to 0 int cnt = 0; for(int i = 0; i < n; i++) { if(!vis[i]) { queue q; vis[i] = 1; q.push(i); cnt++; while(!q.empty()) { int node = q.front(); q.pop(); for(auto it : adjls[node]) { if(!vis[it]) { vis[it] = 1; q.push(it); } } } } } return cnt; } // Without creating Adjacency list ,using given matrix only int findNumOfProvinces(vector& roads, int n) { vector vis(n, 0); // Initialize all values to 0 int cnt = 0; for(int i = 0; i < n; i++) { if(!vis[i]) { queue q; vis[i] = 1; q.push(i); cnt++; while(!q.empty()) { int node = q.front(); q.pop(); for(int j = 0; j < n; j++) { if(roads[node][j] == 1 && !vis[j]) { vis[j] = 1; q.push(j); } } } } } return cnt; }
@ooofrg4492
@ooofrg4492 Ай бұрын
I have problem in time complexity I think it should be o(v^2)+o(v+2e). Am I false then please give reason.
@chirag2819
@chirag2819 4 ай бұрын
Boolean[] vis is better choice then int[] vis
@ayat_middya
@ayat_middya 2 жыл бұрын
Wonderful.....❤️
@suhaanbhandary4009
@suhaanbhandary4009 Жыл бұрын
understood!!
@ashitasrivastava681
@ashitasrivastava681 Жыл бұрын
UNDERSTOOD
G-27. Shortest Path in Directed Acyclic Graph - Topological Sort
26:36
take U forward
Рет қаралды 215 М.
Matching Picture Challenge with Alfredo Larin's family! 👍
00:37
BigSchool
Рет қаралды 52 МЛН
Nurse's Mission: Bringing Joy to Young Lives #shorts
00:17
Fabiosa Stories
Рет қаралды 14 МЛН
The Joker kisses Harley Quinn underwater!#Harley Quinn #joker
00:49
Harley Quinn with the Joker
Рет қаралды 40 МЛН
Master Pointers in C:  10X Your C Coding!
14:12
Dave's Garage
Рет қаралды 303 М.
DSA & ₹1.2 Crore Per Annum Jobs - The Truth? (No Offence)
12:22
CodeWithHarry
Рет қаралды 628 М.
G-9. Flood Fill Algorithm | C++ | Java
20:34
take U forward
Рет қаралды 233 М.
Launching the best DSA Course + Platform
36:29
take U forward
Рет қаралды 208 М.
The Last Algorithms Course You'll Need by ThePrimeagen | Preview
16:44
Frontend Masters
Рет қаралды 317 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 345 М.
G-11. Detect a Cycle in an Undirected Graph using BFS | C++ | Java
20:19
Fastest Way to Learn ANY Programming Language: 80-20 rule
8:24
Sahil & Sarra
Рет қаралды 840 М.
Matching Picture Challenge with Alfredo Larin's family! 👍
00:37
BigSchool
Рет қаралды 52 МЛН