// Example program #include <iostream> #include <string> #include <vector> #include <cmath> #include <unordered_map> #include <algorithm> #include <deque> #include <set> #include <iostream> #include <string> #include <algorithm> #include <algorithm> using namespace std; void BFS(int startnode, const vector<vector<int> >& S){ vector<int> visited(S.size(), 0); visited[startnode] = 1; deque<int> dq; dq.push_back(startnode); while(dq.empty() == false){ int node = dq.front(); dq.pop_front(); cout << node << " "; for(int i = 0; i < S[node].size(); i++){ int neighbor = S[node][i]; // Lấy đỉnh kề if(visited[neighbor] == 0){ // Nếu đỉnh kề chưa được thăm visited[neighbor] = 1; // Đánh dấu đỉnh kề đã được thăm dq.push_back(neighbor); // Thêm đỉnh kề vào deque } } } } void DFS(int node, const vector<vector<int> >& S, vector<int>& visited){ visited[node] = 1; cout << node << " "; for(int i = 0; i < S[node].size(); i++){ if(visited[S[node][i]] == 0){ DFS(S[node][i], S, visited); } } } int main() { int n,m; //số đỉnh, cạnh cin >> n >> m; vector<vector<int> > S(n); vector<int> visited(n,0); for(int i = 0; i < m; i++){ int a,b; cin >> a >> b; S[a].push_back(b); S[b].push_back(a); } DFS(0, S , visited); return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter