1.哈密顿图
#include<bits/stdc++.h>
using namespace std;
const int MAX_V = 507;
int graph[MAX_V][MAX_V];
int n,m,a,b;
int path[MAX_V];
bool visited[MAX_V] = {0};
void print(int path[]){
for (int i=0;i<n;i++) cout<<path[i]<<"->";
cout<<path[0]<<endl;
}
bool hamCycle(int current) {
if (current==n) {
if (graph[path[current - 1]][1]==1) return true;
else return false;
}
for (int v=2;v<=n;v++) {
if (!visited[v] && graph[path[current - 1]][v] == 1) {
visited[v] = true;
path[current] = v;
if (hamCycle(current + 1)) return true;//
path[current] = -1;
visited[v] = false;
}
}
return false;
}
int main() {
cin >>n>>m;
for (int i = 0;i <m;++i){
cin>>a>>b;
graph[a][b]=1;
}
memset(path, -1, sizeof(path));
path[0] = 1;
visited[1] = true;
if (hamCycle(1)==false) {
return 0;
}
else {
print(path);
}
return 0;
}
2.欧拉图
#include <bits/stdc++.h>
using namespace std;
bool mp[107][107];
int n, m;
int flag = 0;
int ans[107];
void dfs(int x, int cnt) {
if (flag) return ;
if (cnt == m + 1) {
flag = 1;
for (int i = 1; i <= m; ++i) {
cout << ans[i] << "->";
}
cout << ans[1];
return ;
}
for (int i = 1; i <= n; ++i) {
if (mp[x][i]) {
mp[x][i] = 0;
ans[cnt] = i;
dfs(i, cnt + 1);
mp[x][i] = 1;
}
}
}
int main() {
cin >> n >>m;
int u, v;
for (int i = 0; i < m; ++i) {
cin >> u >> v;
mp[u][v] = 1;
}
ans[1] = 1;
dfs(1, 2);
return 0;
}