Pagini recente » Cod sursa (job #2736015) | Cod sursa (job #3135888) | Cod sursa (job #1074219) | Cod sursa (job #614025) | Cod sursa (job #2610039)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
const int NMAX = 100005;
bool vizitat[NMAX] = {0};
void read(int &n, int &m, int mat[NMAX][NMAX])
{
fin >> n >> m; int x, y;
for(int i = 0; i < m; i++)
{
fin >> x >> y;
mat[x][y] = 1;
mat[y][x] = 1;
}
}
void DFS(int n, int nod, int mat[NMAX][NMAX])
{
vector <int> solutie;
stack <int> stiva;
solutie.reserve(n + 1);
stiva.push(nod);
solutie.push_back(nod);
vizitat[nod] = 1;
while(!stiva.empty())
{
int i = 1;
while(i <= n && (vizitat[i] || !mat[i][stiva.top()]))
i++;
if(i <= n)
{
vizitat[i] = 1;
solutie.push_back(i);
stiva.push(i);
}
else
stiva.pop();
}
}
int main()
{
int adiacent[NMAX][NMAX] = {0};
int noduri, muchii, conexe = 0;
read(noduri, muchii, adiacent);
for(int i = 1; i <= noduri; i++)
if(!vizitat[i])
{
DFS(noduri, i, adiacent);
conexe++;
}
fout << conexe;
return 0;
}