Given an undirected graph, write an algorithm to check if it is connected (i.e., there is a path between every pair of vertices).
Input Format:
The graph is represented as an adjacency list: a list of n lists, where adj[i] contains all nodes adjacent to node i.
For example, adj = [[1,2],[0,2],[0,1,3],[2]] represents a graph with 4 nodes (0 to 3), where node 0 is connected to nodes 1 and 2, node 1 to 0 and 2, etc.
Input: n =5, adj =[[1],[0,2],[1],[4],[3]]Output: falseExplanation: There are two disconnected components: nodes 0-1-2 and nodes 3-4. Not all nodes are reachable from each other.
classSolution {
public:void dfs(int u, const vector<vector<int>>& adj, vector<bool>& vis) {
vis[u] = true;
for (int v : adj[u]) if (!vis[v]) dfs(v, adj, vis);
}
boolisConnected(int n, vector<vector<int>>& adj) {
vector<bool> vis(n, false);
dfs(0, adj, vis);
for (bool v : vis) if (!v) return false;
return true;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicbooleanisConnected(int n, List<List<Integer>> adj) {
boolean[] vis =newboolean[n];
dfs(0, adj, vis);
for (boolean v : vis) if (!v) returnfalse;
returntrue;
}
privatevoiddfs(int u, List<List<Integer>> adj, boolean[] vis) {
vis[u]=true;
for (int v : adj.get(u)) if (!vis[v]) dfs(v, adj, vis);
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defis_connected(self, n: int, adj: list[list[int]]) -> bool:
vis = [False] * n
defdfs(u):
vis[u] =Truefor v in adj[u]:
ifnot vis[v]:
dfs(v)
dfs(0)
return all(vis)