Problem :You are given an unweighted, undirected graph. Example Input: 3 2 1 2 2 3 Output: YES Write a program to check if it's a tree topology.
I think there is some problem in graph initialization, I tried using vector <vector <int>> graph, but my code crashed again. Can anybody tell me what is the problem with my code?
#include <bits/stdc++.h>using namespace std;const int MAX_N =100005;bool visited[MAX_N];void dfs(int s, vector <int> graph[]){visited[s]=true;for(auto neighbour : graph[s]){if (!visited[neighbour]){dfs(neighbour, graph);}}}void initialize(int nodes) {for(int i = 1;i<=nodes;++i)visited[i] = false;}int main(){int n, m, x, y, connectedComponents=0;cin >> n >> m;vector<int> graph[n];for (int i=0;i<m;i++){cin >> x >> y;graph[x].push_back(y);graph[y].push_back(x);}initialize(n);for(int i = 1;i <= n ;++i) {if(visited[i] == false) {dfs(i, graph);connectedComponents++;}}if(connectedComponents==n && m==n-1){cout << "Yes";}cout << "Number of connected components: " << connectedComponents << endl;return 0;}