TheAlgorithms-C-Plus-Plus/graph/BFS.cpp

74 lines
1.2 KiB
C++
Raw Normal View History

2020-04-18 10:43:43 +08:00
#include <iostream>
2016-11-29 00:48:08 +08:00
using namespace std;
2019-08-21 10:10:08 +08:00
class graph
{
2016-11-29 00:48:08 +08:00
int v;
list<int> *adj;
2019-08-21 10:10:08 +08:00
public:
2016-11-29 00:48:08 +08:00
graph(int v);
2019-08-21 10:10:08 +08:00
void addedge(int src, int dest);
2016-11-29 00:48:08 +08:00
void printgraph();
void bfs(int s);
};
2019-08-21 10:10:08 +08:00
graph::graph(int v)
{
2016-11-29 00:48:08 +08:00
this->v = v;
this->adj = new list<int>[v];
}
2019-08-21 10:10:08 +08:00
void graph::addedge(int src, int dest)
{
src--;
dest--;
2016-11-29 00:48:08 +08:00
adj[src].push_back(dest);
//adj[dest].push_back(src);
}
2019-08-21 10:10:08 +08:00
void graph::printgraph()
{
for (int i = 0; i < this->v; i++)
{
cout << "Adjacency list of vertex " << i + 1 << " is \n";
2016-11-29 00:48:08 +08:00
list<int>::iterator it;
2019-08-21 10:10:08 +08:00
for (it = adj[i].begin(); it != adj[i].end(); ++it)
{
cout << *it + 1 << " ";
2016-11-29 00:48:08 +08:00
}
2019-08-21 10:10:08 +08:00
cout << endl;
2016-11-29 00:48:08 +08:00
}
}
2019-08-21 10:10:08 +08:00
void graph::bfs(int s)
{
bool *visited = new bool[this->v + 1];
memset(visited, false, sizeof(bool) * (this->v + 1));
visited[s] = true;
2016-11-29 00:48:08 +08:00
list<int> q;
q.push_back(s);
list<int>::iterator it;
2019-08-21 10:10:08 +08:00
while (!q.empty())
{
2016-11-29 00:48:08 +08:00
int u = q.front();
2019-08-21 10:10:08 +08:00
cout << u << " ";
2016-11-29 00:48:08 +08:00
q.pop_front();
2019-08-21 10:10:08 +08:00
for (it = adj[u].begin(); it != adj[u].end(); ++it)
{
if (visited[*it] == false)
{
2016-11-29 00:48:08 +08:00
visited[*it] = true;
q.push_back(*it);
}
}
}
}
2019-08-21 10:10:08 +08:00
int main()
{
2016-11-29 00:48:08 +08:00
graph g(4);
2019-08-21 10:10:08 +08:00
g.addedge(1, 2);
g.addedge(2, 3);
g.addedge(3, 4);
g.addedge(1, 4);
g.addedge(1, 3);
2016-11-29 00:48:08 +08:00
//g.printgraph();
g.bfs(2);
return 0;
2019-02-17 20:28:40 +08:00
}