1 <? PHP 2 # has n strings, and each array has a length of m + 1. If the rear M elements of the array are the same as the first M elements of the other array, then the two Arrays can be connected. 3 # calculate the maximum number of connected paths in N arrays. If a loop is encountered, an error is returned and the 4 5 function longest ($ A, $ m) function is exited) {6 $ Len = count ($ A); 7 # Treat each string element of the Two-dimensional array $ A as a node 8 # create an array of connection relationships between nodes g, G [I] [J] indicates the longest path between node IJ 9 10 # initialize G. The value of the connectable node is set to 111 $ G = array (); 12 For ($ I = 0; $ I <$ Len; $ I ++) {13 for ($ J = 0; $ j <$ Len; $ J ++) {14 $ lastm = substr ($ A [$ I], 1); 15 $ firstm = substr ($ A [$ J], 0, $ m ); 16 if ($ lastm = $ firs TM) {17 $ G [$ I] [$ J] = 1; 18} else {19 $ G [$ I] [$ J] = 0; 20} 21} 22} 23 24 # use the fresh algorithm to calculate the longest path 25 for ($ k = 0; $ k <$ Len; $ K ++) {26 for ($ I = 0; $ I <$ Len; $ I ++) {27 for ($ J = 0; $ j <$ Len; $ J ++) {28 if ($ G [$ I] [$ K]> 0 & $ G [$ K] [$ J]> 0) {29 $ Dist = $ G [$ I] [$ K] + $ G [$ K] [$ J]; 30 if ($ Dist> $ G [$ I] [$ J]) {31 $ G [$ I] [$ J] = $ Dist; 32} 33} 34} 35} 36} 37 38 # detection loop 39 # two types of loops are available: I-> I self-to myself, and the other is, i->... -> K->... -> i40 for ($ I = 0; $ I <$ Len; $ I ++) {41 if ($ G [$ I] [$ I]> = 1) die ("there is a circle"); 42} 43 44 # Find the longest path 45 $ max = 0; 46 for ($ I = 0; $ I <$ Len; $ I ++) {47 $ max = max ($ G [$ I]), $ max); 48} 49 50 return $ Max; 51} 52 53 $ A = array (54 "ABCD", 55 "bcde", 56 "cdea", 57 "Deab", 58 "EABA", 59 "Abab ", 60 "Deac", 61 "cdei", 62 "bcdf", 63 "Color Doppler", 64 "DFIC", 65 "cdfk", 66 "bcdg", 67 ); 68 69 print_r (longest ($ A, 3); 70?>