Pagini recente » Cod sursa (job #637767) | Cod sursa (job #1052303) | Cod sursa (job #1168651) | Cod sursa (job #925529) | Cod sursa (job #2467176)
// BFS.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
//#include "pch.h"
#include <iostream>
#include <fstream>
#include <queue>
#include <deque>
#define MAXV 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
struct edgeNode {
int value;
int weight;
edgeNode * next;
};
class Graph {
private:
int nEdges, nVertices;
bool directed;
deque<edgeNode *> adjacencyList;
deque<int> degree;
public:
void initialiseGraph() {
for (int i = 1; i <= MAXV; ++i) {
adjacencyList.push_back(nullptr);
}
for (int i = 1; i <= MAXV; ++i) {
degree.push_back(0);
}
}
void readGraph(bool directed, int nVertices, int nEdges) {
int x, y;
this->directed = directed;
this->nVertices = nVertices;
this->nEdges = nEdges;
initialiseGraph();
for (int i = 1; i <= nEdges; ++i) {
fin >> x >> y;
if(x != y)
insertEdge(y, x, directed);
}
}
void insertEdge(int x, int y, bool directed) {
edgeNode * newVertex = new edgeNode;
newVertex->value = x;
newVertex->next = adjacencyList.at(y);
adjacencyList.at(y) = newVertex;
degree.at(x)++;
if (directed == false) {
insertEdge(y, x, !directed);
}
}
/*void printGraph() {
edgeNode * neighbor;
for(int i = 0; i <= nVertices; ++i)
if (adjacencyList.at(i) != nullptr) {
fout << i << " : ";
neighbor = adjacencyList.at(i);
while (neighbor != nullptr) {
fout << neighbor->value << " ";
neighbor = neighbor->next;
}
fout << endl;
}
}*/
void bfs(int start, int N) {
deque<int>dp;
for (int i = 0; i <= N; ++i) {
dp.push_back(-1);
}
dp[start] = 0;
queue<int> vertices;
vertices.push(start);
while (!vertices.empty()) {
int x = vertices.front();
vertices.pop();
edgeNode * p = adjacencyList.at(x);
while (p != nullptr) {
if (dp[p->value] == -1) {
dp[p->value] = dp[x] + 1;
vertices.push(p->value);
}
p = p->next;
}
}
for (int i = 1; i <= N; i++)
fout << dp[i] << " ";
}
};
int main()
{
int N, M, S;
fin >> N >> M >> S;
Graph g;
g.readGraph(true, N, M);
g.bfs(S, N);
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file