joj 1509Hamiltonian Cycle (dfs求H回路)

 

利用了Hamiltonian路的一些性质

#include <cstdio>
#include <memory.h>
#include <iostream>

// practice for hamilton graph and dfs.

using namespace std;

const int maxn=1000;
bool map[maxn][maxn];
int path[maxn];
bool vis[maxn];
int n , edge;
bool flag;
void dfs (int x,int cnt)//recursion with recall
{
    if(cnt==(n-1))
    {
        if(!flag)
        if(map[x][1])
        {
            printf("1");
            for (int i=0 ; i<n-1 ; i++)
             printf(" %d",path[i]);
            printf(" 1\n");
            flag=true;
        }
        return ;
    }//
    for (int i=1 ; i<=n  ; i++)
    {
        if(!vis[i] && map[i][x])
        {
             vis[i]=1;
             path[cnt]=i;
             //printf("%d\t",path[cnt]);
             dfs(i,cnt+1);
             //printf(" %d",i);
             vis[i]=0;
        }
    }
}

int main ()
{
    char s;
    int cnt;
    int u;
    int v;
    while (scanf("%d",&n)!=EOF)
    {
          memset (vis , 0 , sizeof(vis));
          memset (map , 0 , sizeof(map));
          flag=false;
          for (cnt=0 ;;cnt++)
          {
              getchar();
              scanf("%c",&s);
              if(s=='%')break;
              scanf("%d",&u);
              v=s-48;
              //printf("%d %d",v,u);
              map[v][u]=true;
              map[u][v]=true;
          }
          edge=cnt;
          if(n>2){vis[1]=1;dfs(1,0);}//begin with 0th,point1
          else printf("N\n");//这里要考虑下点数小于3的情况
    }
    return 0;
}

你可能感兴趣的:(c,Graph,Path,n2)