Pagini recente » Cod sursa (job #1788189) | Cod sursa (job #1775103) | Cod sursa (job #806465) | Cod sursa (job #1680209) | Cod sursa (job #2786015)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
class Graph {
std::vector<std::vector<int>> Ad;
int nodes;
int size;
std::vector<int> vis;
public:
Graph(const std::vector<std::pair<int,int>> &ad, int nodes, int size,int directed);
void DFS(int node);
int getComponents();
void BFS(int node);
void pathTo(int node);
};
Graph::Graph(const std::vector<std::pair<int,int>> &ad, int nodes, int size, int directed) : nodes(nodes), size(size) {
Ad.resize(nodes+1);
for(int i = 0; i<size; ++i){
Ad[ad[i].first].push_back(ad[i].second);
if(directed == 0)
Ad[ad[i].second].push_back(ad[i].first);
}
}
void Graph::DFS(int node){
vis[node] = 1;
for(int i = 0; i<Ad[node].size(); ++i)
if(vis[Ad[node][i]] == 0){
DFS(Ad[node][i]);
}
}
int Graph::getComponents() {
int ct = 0;
vis.resize(nodes);
std::fill(vis.begin(), vis.end(), 0);
for(int i = 1;i <= nodes; ++i)
if(vis[i] == 0){
DFS(i);
ct++;
}
return ct;
}
void Graph::BFS(int node){
int parent, distance;
std::queue<pair<int,int>> Q;
Q.push({node,-1});
while(!Q.empty()){
parent = Q.front().first;
distance = Q.front().second;
Q.pop();
vis[parent] = distance + 1;
for(int i = 0; i<Ad[parent].size(); ++i)
if(vis[Ad[parent][i]] == -1){
Q.push({Ad[parent][i], distance + 1});
}
}
}
void Graph::pathTo(int node){
vis.resize(nodes+1);
std::fill(vis.begin(), vis.end(), -1);
vis[node] = 0;
BFS(node);
for(int i = 1; i<= nodes; ++i)
fout << vis[i] << " ";
}
int main() {
std::vector<std::pair<int,int>> Ad;
int n,m,x,y,s;
fin >> n >> m >> s;
for(int i = 0; i<m; ++i){
fin >> x >> y;
Ad.push_back({x,y});
}
Graph G(Ad,n ,m, 1);
G.pathTo(s);
return 0;
}