Advertisement
jayati

Number of Provinces

May 17th, 2024
492
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     void dfs(int node, vector<vector<int>>& isConnected, vector<bool>& visit) {
  4.         visit[node] = true;
  5.         for (int i = 0; i < isConnected.size(); i++) {
  6.             if (isConnected[node][i] && !visit[i]) {
  7.                 dfs(i, isConnected, visit);
  8.             }
  9.         }
  10.     }
  11.  
  12.     int findCircleNum(vector<vector<int>>& isConnected) {
  13.         int n = isConnected.size();
  14.         int numberOfComponents = 0;
  15.         vector<bool> visit(n);
  16.  
  17.         for (int i = 0; i < n; i++) {
  18.             if (!visit[i]) {
  19.                 numberOfComponents++;
  20.                 dfs(i, isConnected, visit);
  21.             }
  22.         }
  23.  
  24.         return numberOfComponents;
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement