回溯法求解欧拉图与哈密顿图

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;
}
 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值