Created
May 3, 2017 17:11
-
-
Save echo-akash/b84a8dbdcbe1006c84da3f19fdf995bb to your computer and use it in GitHub Desktop.
Implement Breadth First Search in Graph using Adjacency Matrix in c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <cstdlib> | |
| using namespace std; | |
| #define MAX 20 | |
| class AdjacencyMatrix | |
| { | |
| private: | |
| int n; | |
| int **adj; | |
| bool *visited; | |
| public: | |
| AdjacencyMatrix(int n) | |
| { | |
| this->n = n; | |
| visited = new bool [n]; | |
| adj = new int* [n]; | |
| for (int i = 0; i < n; i++) | |
| { | |
| adj[i] = new int [n]; | |
| for(int j = 0; j < n; j++) | |
| { | |
| adj[i][j] = 0; | |
| } | |
| } | |
| } | |
| void add_edge(int origin, int destin) | |
| { | |
| if( origin > n || destin > n || origin < 0 || destin < 0) | |
| { | |
| cout<<"Invalid edge!\n"; | |
| } | |
| else | |
| { | |
| adj[origin - 1][destin - 1] = 1; | |
| } | |
| } | |
| void display() | |
| { | |
| int i,j; | |
| for(i = 0;i < n;i++) | |
| { | |
| for(j = 0; j < n; j++) | |
| cout<<adj[i][j]<<" "; | |
| cout<<endl; | |
| } | |
| } | |
| }; | |
| int main() | |
| { | |
| int nodes, max_edges, origin, destin; | |
| cout<<"Enter number of nodes: "; | |
| cin>>nodes; | |
| AdjacencyMatrix am(nodes); | |
| max_edges = nodes * (nodes - 1); | |
| for (int i = 0; i < max_edges; i++) | |
| { | |
| cout<<"Enter edge (-1 -1 to exit): "; | |
| cin>>origin>>destin; | |
| if((origin == -1) && (destin == -1)) | |
| break; | |
| am.add_edge(origin, destin); | |
| } | |
| am.display(); | |
| return 0; | |
| } |
This is just a matrix not a BFS.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure where you breadth first search is...