Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- input:
- 6 6
- 1 2
- 1 5
- 2 3
- 2 4
- 3 4
- 3 6
- */
- #include <iostream>
- #include <fstream>
- using namespace std;
- class Graph
- {
- private:
- int nrNodes;
- int matrix[100][100];
- int viz[100];
- int queue[100];
- public:
- Graph()
- {
- nrNodes = 100;
- for (int i = 1; i <= nrNodes; i++)
- {
- viz[i] = 0;
- queue[i] = 0;
- for(int j = 1; j <= nrNodes; j++)
- matrix[i][j] = 0;
- }
- }
- void reinit()
- {
- for(int i = 1; i<= nrNodes; i++)
- viz[i] = 0;
- }
- void readGraph();
- void DFS(int current);
- void BFS(int start);
- };
- void Graph::readGraph()
- {
- int firstNode, secondNode;
- ifstream f("input.txt");
- int nrOfEdges;
- f>>nrOfEdges;
- f>>nrNodes;
- for(int i = 1; i <= nrOfEdges; i++)
- {
- f>>firstNode>>secondNode;
- matrix[firstNode][secondNode] = matrix[secondNode][firstNode] = 1;
- }
- f.close();
- }
- void Graph::DFS(int current)
- {
- if (viz[current] == 1)
- return;
- viz[current] = 1;
- cout<<current<<' ';
- for (int i = 1; i <= nrNodes; i++)
- if(matrix[current][i] == 1)
- DFS(i);
- }
- void Graph::BFS(int start)
- {
- queue[1] = start;
- viz[start] = 1;
- int p = 1, u = 1;
- int current;
- while (p <= u)//coada nevida
- {
- current = queue[p];
- p++;
- cout<<current<<' ';
- for (int i = 1; i <= nrNodes; i++)
- if (matrix[current][i] == 1 && viz[i] == 0)
- {
- u++;
- queue[u] = i;
- viz[i] = 1;
- }
- }
- }
- int main()
- {
- Graph g;
- g.readGraph();
- cout<<"DFS: ";
- g.DFS(1);
- cout<<endl;
- g.reinit();
- cout<<"BFS: ";
- g.BFS(1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement