You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
#include<utility>voidDfs(int n, int v);
voidBfs(int n, int v);
std::vector<std::vector<int>> g;
std::vector<bool> is_visited;
intmain() {
int n, m, v;
std::cin >> n >> m >> v;
g = std::vector<std::vector<int>>(n + 1, std::vector<int>(n + 1));
while (m--) {
int x, y;
std::cin >> x >> y;
g[x][y] = g[y][x] = 1;
}
Dfs(n, v);
std::cout << '\n';
Bfs(n, v);
return0;
}
voidDfs(int n, int v) {
std::stack<int> s;
s.push(v);
is_visited = std::vector<bool>(n + 1);
while (!s.empty()) {
auto cur = s.top();
s.pop();
if (is_visited[cur])
continue;
is_visited[cur] = true;
std::cout << cur << '';
// NOTICE: Search in reverse order considering the characteristics of the// stackfor (int i = n; i > 0; --i) {
if (is_visited[i])
continue;
if (!g[cur][i])
continue;
s.push(i);
}
}
return;
}
voidBfs(int n, int v) {
std::queue<int> q;
q.push(v);
is_visited = std::vector<bool>(n + 1);
is_visited[v] = true;
while (!q.empty()) {
auto cur = q.front();
q.pop();
std::cout << cur << '';
for (int i = 1; i <= n; ++i) {
if (is_visited[i])
continue;
if (!g[cur][i])
continue;
q.push(i);
is_visited[i] = true;
}
}
return;
}
#include<iostream>
#include<vector>voidBt(int);
std::vector<int> arr;
std::vector<bool> is_visited;
int n, m;
intmain() {
std::cin >> n >> m;
arr = std::vector<int>(n + 1);
is_visited = std::vector<bool>(n + 1);
Bt(0);
return0;
}
voidBt(int s) {
if (s == m) {
for (int i = 0; i < m; ++i)
std::cout << arr[i] << '';
std::cout <<'\n';
return;
}
for (int i = 1; i <= n; ++i) {
if (is_visited[i])
continue;
arr[s] = i;
// Go as deeply as possible, backtrack if impossible
is_visited[i] = true;
Bt(s + 1);
is_visited[i] = false;
}
return;
}