Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<fstream>
- #include<vector>
- #include<queue>
- #define MAX_SIZE 100
- typedef std::vector<int> graph;
- void read_from_file(graph G[], int &source)
- {
- std::ifstream in("file_bfs_dfs.txt");
- if (!in.is_open())
- std::cout << "The file wasn't opened!\n";
- else
- {
- int n; //nr de noduri
- in >> n;
- in >> source;
- int x, y; //extremitatile fiecarei muchii
- while (in >> x >> y)
- {
- G[x].push_back(y);
- G[y].push_back(x);
- }
- }
- }
- void bfs(graph G[], int source)
- {
- std::queue<int> Q;
- Q.push(source);
- std::vector<int> visited(MAX_SIZE,0);
- visited[source] = 1;
- while (!Q.empty())
- {
- int v_curent = Q.front();
- Q.pop();
- std::cout << v_curent <<" ";
- for (int i = 0; i < G[v_curent].size(); i++)
- {
- if (!visited[G[v_curent][i]])
- {
- visited[G[v_curent][i]] = 1;
- Q.push(G[v_curent][i]);
- }
- }
- }
- std::cout << std::endl;
- }
- std::vector<bool> vis_dfs(MAX_SIZE, 0);
- #include<stack>
- void dfs (int source)
- {
- std::stack<int> S;
- S.push(source);
- while (!S.empty())
- {
- int curent = S.top();
- S.pop();
- if (!vis_dfs[curent])
- {
- vis_dfs[curent] = 1;
- //std::cout << curent << " ";
- for (int i = 0; i < g[curent].size(); i++)
- {
- if (g[curent][i]==1 && !vis_dfs[i])
- S.push(i);
- }
- }
- }
- //std::cout << std::endl;
- }
- int main()
- {
- graph G[MAX_SIZE];
- int source;
- read_from_file(G,source);
- std::cout << "----BFS----\n";
- bfs(G,source);
- std::cout << "-----DFS-----\n";
- dfs(G, source);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement