Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<queue>
- using namespace std;
- #define size 10
- class graph{
- int adjacency[size][size]; // adjacency matrix
- int vertices;
- int visited_array[size];
- public:
- graph(){
- for(int i = 0; i < size; i++){
- for(int j = 0; j < size; j++){
- adjacency[i][j] = 0;
- }
- }
- vertices = 0;
- for(int i = 0; i < vertices; i++){
- visited_array[i] = 0;
- }
- }
- graph(int v){
- for(int i = 0; i < size; i++){
- for(int j = 0; j < size; j++){
- adjacency[i][j] = 0;
- }
- }
- vertices = v;
- for(int i = 0; i < size; i++){
- visited_array[i] = 0;
- }
- }
- //void create();
- void add_edge(int v1, int v2){
- adjacency[v1][v2] = 1;
- adjacency[v2][v1] = 1;
- }
- void display(){
- for(int i = 0; i < vertices; i++){
- for(int j = 0; j < vertices; j++){
- cout << adjacency[i][j] << " ";
- }
- cout << endl;
- }
- }
- void bfs(int v){
- queue<int> q;
- int visited[vertices] = {0};
- q.push(v);
- visited[v] = 1;
- while(!q.empty()){
- int printVertex = q.front();
- q.pop();
- cout << printVertex << " ";
- for(int i = 0; i < vertices; i++){
- if(adjacency[printVertex][i] == 1 && (visited[i] == 0)){
- q.push(i);
- visited[i] = 1;
- }
- }
- }
- cout << endl;
- }
- void dfs(int v){
- int v2 = 0;
- cout << "v: " << v << endl;
- visited_array[v] = 1;
- for(v2 = 0; v2 < vertices; v2++){
- if((adjacency[v][v2] == 1)){
- if(visited_array[v2] == 0){
- dfs(v2);
- }
- }
- }
- }
- };
- int main(){
- graph g(6);
- g.add_edge(1, 2);
- g.add_edge(5, 2);
- g.add_edge(1, 0);
- g.add_edge(2, 3);
- g.add_edge(3, 4);
- g.bfs(1);
- g.dfs(1);
- g.display();
- return 0;
- };
Add Comment
Please, Sign In to add comment