next up previous contents
Next: Greedy Algorithms Up: NP-Completeness Previous: Hamilton Cycle   Contents

Longest Path: Introduction [203]




\begin{picture}(568,219)(26,600)
\thicklines\put(120,720){\circle{28}}
\put( 40,...
...(505,625){\makebox(0,0)[lb]{\raisebox{0pt}[0pt][0pt]{\twlrm 100}}}
\end{picture}



Find the longest path (or distance) in G.

Visit each node at most one time (except the START=1).

Algorithm: exhaustive search - try all paths.

Analysis: very slow.



LP: Pseudocode [204]

int A[MAX][MAX};
int visited[MAX];

int LP(int v) {
int w, dist, max = 0;
  visited[v] = TRUE;
  for (all neighbors w of v)
    if (!visited[w]) {
      dist = A[v][w] + LP(w);
      if (dist > max)
        max = dist; 
    }
  visited[v] = FALSE;
  return(max);
}



LP: long [205]

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

Data File with Test Case: long.dat

5
1 1 1 1 0
1 1 1 0 2
1 1 1 1 1 
1 0 1 1 1
0 2 1 1 1

% long long.dat
n: 5 steps: 55

% long complete.dat 4
n: 4 steps: 30
% long complete.dat 6
n: 6 steps: 650
% long complete.dat 8
n: 8 steps: 27398
% long complete.dat 10
n: 10 steps: 1972818

ANALYSIS: O(      ) = O(      )



LP: long.dat [206]

% long long.dat step
 u  v step         u  v step         u  v step         u  v step
----------------------------------------------------------------
 1  2    1         4  1   15         4  5   29         2  5   43        
 2  1    2         5  4   16         5  2   30         3  5   44        
 2  3    3         4  1   17         2  1   31         5  2   45        
 3  1    4         4  3   18         3  5   32         2  1   46        
 3  4    5         3  1   19         5  2   33         4  5   47        
 4  1    6         1  3   20         2  1   34         5  2   48        
 4  5    7         3  1   21         5  4   35         2  1   49        
 3  5    8         3  2   22         4  1   36         2  3   50        
 5  4    9         2  1   23         1  4   37         3  1   51        
 4  1   10         2  5   24         4  1   38         5  3   52        
 2  5   11         5  4   25         4  3   39         3  1   53        
 5  3   12         4  1   26         3  1   40         3  2   54        
 3  1   13         3  4   27         3  2   41         2  1   55        
 3  4   14         4  1   28         2  1   42 

Longest Distance: 6



LP: long.c [207]

#define START 1
int n, label = 0;
int val[MAX], A[MAX]MAX];

int LP(int v) {
int w, dist = 0, max = 0;
  val[v] = ++label;
  for (w=1; w<=n; w++) 
    if (A[v][w]) {
      if (val[w] == 0)  
        dist = A[v][w] + LP(w);
      else
      if ((w == START) && (v != w)) 
        dist = A[v][w];
      if (dist > max) 
        max = dist;
    }
  label--;
  val[v] = 0;
  return(max);
}
main(int argc, char *argv[]) {
int longest_distance;
   longest_distance = LP(START); 
}



Ted Billard 2001-10-25