next up previous contents
Next: Longest Path: Introduction Up: NP-Completeness Previous: NP-Completeness   Contents

Hamilton Cycle [197]




\begin{picture}(449,214)(26,600)
\thicklines\put(120,720){\circle{28}}
\put( 40,...
...60,600){\makebox(0,0)[lb]{\raisebox{0pt}[0pt][0pt]{\twlrm Cycle}}}
\end{picture}

Connect all nodes without a second visit (except the START=1).

Algorithm: exhaustive search - try all possible paths.

Analysis: very slow.



HC: Pseudocode [198]

int A[MAX][MAX];           /* original graph             */
int B[MAX][MAX];           /* current working path       */
int visited[MAX];          /* has node been touched yet? */

int HC(int v)
int w;
  visited[v] = TRUE;
  if (v is last node to be visited)
    if (A[v][w]) return(TRUE);
  for (all neighbors w of v)
    if (!visited[w]) {
      B[v][w] = 1;         /* guess that v,w is on cycle */
      if (HC(w))
        return(TRUE);
      else
        B[v][w] = 0;       /* guess turned out wrong     */
  
  visited[v] = FALSE;
  return(FALSE);
}



HC: hc (Cycle Found) [199]

% gcc -o hc hc.c                                       > tcc hc.c

Data File with Test Case: hc.dat

5
1 1 1 1 0
1 1 1 0 1
1 1 1 1 1 
1 0 1 1 0
0 1 1 0 1

% hc hc.dat
n: 5 steps: 8

% hc hc.dat graph
Cycle found.
n: 5 steps: 8
  0  1  0  0  0
  0  0  0  0  1
  0  0  0  1  0
  1  0  0  0  0
  0  0  1  0  0



HC: hc.dat (Cycle Found) [200]

% hc hc.dat step
 v  w step
 1  2    1 +
 2  3    2 +
 3  4    3 +
 3  4    4 -
 3  5    4 +
 3  5    5 -
 2  3    5 -
 2  5    5 +
 5  3    6 +
 3  4    7 +
 4  1    8 *

Path 1, 2, 3, 4 did not work.

Path 1, 2, 3, 5 did not work.

Path 1, 2, 5, 3, 4 worked.



HC: hc4.dat (Not Found) [201]

4
1 1 1 1 
1 1 1 1 
1 1 1 1 
0 0 0 0      # fully-connected nodes except last node fails

% hc hc4.dat step
 u  v step         u  v step         u  v step
------------------------------------------------
 1  2    1 +       2  4    5 -       3  2    8 -      
 2  3    2 +       1  2    5 -       3  4    8 +      
 3  4    3 +       1  3    5 +       3  4    9 -      
 3  4    4 -       3  2    6 +       1  3    9 -      
 2  3    4 -       2  4    7 +       1  4    9 +      
 2  4    4 +       2  4    8 -       1  4   10 -      

% hc hc4.dat
n: 4 steps: 10
% hc hc6.dat
n: 6 steps: 130
% hc hc8.dat
n: 8 steps: 3914
% hc hc10.dat
n: 10 steps: 219202
ANALYSIS: O(      ) = O(      )



HC: hc.c [202]

#define START 1
int n, A[MAX][MAX], B[MAX][MAX], val[MAX];
int label = 0;
int HC(int v) {
int w;
  val[v] = ++label;
  if ((val[v] == n) && (A[v][START])) {
    B[v][START] = 1; 
    return(1);
  }
  for (w=1; w<=n; w++) 
    if (A[v][w]) 
      if (val[w] == 0) {
        B[v][w] = 1; 
        if (HC(w)) 
          return(1);
        else 
          B[v][w] = 0;  
      }
  label--;
  val[v] = 0;
  return(0);
}
if (HC(START)) then printf("Found\n") else printf("Not Found\n");



Ted Billard 2001-10-25