Pagini recente » Cod sursa (job #1100999) | Cod sursa (job #2231833) | Cod sursa (job #1169300) | Cod sursa (job #2393981) | Cod sursa (job #2304160)
#include <fstream>
#include <vector>
using namespace std;
ifstream in("dfs.in");
ofstream out("dfs.out");
const int MAX_SIZE = 100005;
vector <int> v[MAX_SIZE];
int st[MAX_SIZE]; ///stack
bool vis[MAX_SIZE]; ///visited nodes
void DFS(int n, int src){
int h = 1;
int top, sz;
st[1] = src;
while(h > 0){
top = st[h--];
if(vis[top] == false){
vis[top] = true;
sz = v[top].size();
for(int i=0;i<sz;i++)
st[++h] = v[top][i];
}
}
}
int main()
{
int n, m, x, y, nrConex = 0;
in>>n>>m;
for(int i=1;i<=m;i++){
in>>x>>y;
v[x].push_back(y);
v[y].push_back(x);
}
in.close();
for(int i=1;i<=n;i++)
if(vis[i] == false){
nrConex++;
DFS(n, i);
}
out<<nrConex<<"\n";
out.close();
return 0;
}