可能是因为从1到终点的路上并不包括所有的结点,所以需要预处理下,把路径上的所有点给挑出来,然后在这个路径上进行回溯就OK了,直接回朔是要TLE的...... #include <iostream> #include <cstring> #include <cstdio> #include <cstdlib> #include <cmath> using namespace std ; const int maxn = 22 ; int g[maxn][maxn] , d , n ; int vis[maxn] , ans , cnt , route[maxn] , node[maxn] , ncnt ; void init() { memset( vis , 0 , sizeof( vis ) ) ; memset( route , 0 , sizeof( route ) ) ; memset( g , 0 , sizeof( g ) ) ; memset( node , 0 , sizeof( node ) ) ; n = 0 ; ans = 0 ; cnt = 0 ; ncnt = 0 ; return ; } int cmp( const void * _a , const void * _b ) { int * a = ( int * ) _a ; int * b = ( int * ) _b ; return *a - *b ; } void input() { int u , v ; while( cin >> u >> v && u ) { if( u > n ) n = u ; if( v > n ) n = v ; g[u][v] = g[v][u] = 1 ; } return ; } void dfs( int u ) { if( u == d ) { ans++ ; int cc = 0 ; for( int i = 0 ; i < cnt ; ++i ) if( ++cc < cnt ) cout << route[i] << " " ; else cout << route[i] ; cout << endl ; return ; } for( int v = 0 ; v < ncnt ; ++v ) if( g[u][node[v]] && !vis[node[v]] ) { vis[node[v]] = 1 ; route[cnt++] = node[v] ; dfs( node[v] ) ; cnt-- ; vis[node[v]] = 0 ; } return ; } void dfs_init( int u ) { vis[u] = 1 ; node[ncnt++] = u ; for( int v = 1 ; v <= n ; ++v ) if( g[u][v] && !vis[v] ) { dfs_init( v ) ; } return ; } void solve() { dfs_init( d ) ; qsort( node , ncnt , sizeof( int ) , cmp ) ; memset( vis , 0 , sizeof( vis ) ) ; vis[1] = 1 ; route[cnt++] = 1 ; dfs( 1 ) ; vis[1] = 0 ; return ; } void output() { cout << "There are " << ans << " routes from the firestation to streetcorner " << d << "." << endl ; return ; } int main() { int icase = 1 ; while( cin >> d ) { cout << "CASE " << icase++ << ":" << endl ; init() ; input() ; solve() ; output() ; } return 0 ; }