Pagini recente » Cod sursa (job #904600) | Cod sursa (job #2960120) | Cod sursa (job #1440957) | Cod sursa (job #2525280) | Cod sursa (job #2668422)
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <stack>
using namespace std;
int main()
{
ifstream fi("dfs.in");
ofstream fo("dfs.out");
int m, n;
fi >> n >> m;
vector<list<int>> graph(n);
for (int i = 0; i < m; i++) {
int a, b;
fi >> a >> b;
a--;
b--;
graph[a].push_back(b);
graph[b].push_back(a);
}
vector<bool> visited(n, false);
stack<int> st;
int count = 0;
bool more = false;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
st.push(i);
visited[i] = true;
more = true;
break;
}
}
while(more) {
more = false;
count++;
while (st.size() > 0) {
int node = st.top();
st.pop();
for (int i : graph[node]) {
if (!visited[i]) {
st.push(i);
visited[i] = true;
}
}
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
st.push(i);
visited[i] = true;
more = true;
break;
}
}
}
fo << count;
fi.close();
fo.close();
return 0;
}