1
+ """
2
+ #246
3
+ Dropbox
4
+
5
+ Given a list of words, determine whether the words can be chained to form a circle.
6
+ A word X can be placed in front of another word Y in a circle if the last character of X is same as the first character of Y.
7
+
8
+ For example, the words ['chair', 'height', 'racket', 'touch', 'tunic'] can form the following circle:
9
+ chair --> racket --> touch --> height --> tunic --> chair.
10
+
11
+ """
12
+
13
+ def checkForCycleHelper (usedWords , remainingWords ):
14
+ if len (remainingWords ) == 0 :
15
+ # print(usedWords, end=" ") # Uncomment to see the chain
16
+ return True
17
+
18
+ lastLetter = usedWords [- 1 ][- 1 ]
19
+ for i in range (len (remainingWords )):
20
+ nextWord = remainingWords [i ]
21
+ if nextWord .startswith (lastLetter ) and checkForCycleHelper (usedWords + [nextWord ], remainingWords [:i ]+ remainingWords [i + 1 :]):
22
+ return True
23
+
24
+ return False
25
+
26
+
27
+ def checkForCycle (words ):
28
+ return checkForCycleHelper ([words [0 ]], words [1 :])
29
+
30
+ def main ():
31
+ print (checkForCycle (["geek" , "king" ])) # True ['geek', 'king']
32
+ print (checkForCycle (["for" , "geek" , "rig" , "kaf" ])) # True ['for', 'rig', 'geek', 'kaf']
33
+ print (checkForCycle (["aab" , "bac" , "aaa" , "cda" ])) # True ['aab', 'bac', 'cda', 'aaa']
34
+ print (checkForCycle (["aaa" , "bbb" , "baa" , "aab" ])) # True ['aaa', 'aab', 'bbb', 'baa']
35
+ print (checkForCycle (["aaa" ])) # True ['aaa']
36
+ print (checkForCycle (["aaa" , "bbb" ])) # False
37
+ print (checkForCycle (["abc" , "efg" , "cde" , "ghi" , "ija" ])) # True ['abc', 'cde', 'efg', 'ghi', 'ija']
38
+ print (checkForCycle (["ijk" , "kji" , "abc" , "cba" ])) # False
39
+
40
+
41
+ if __name__ == "__main__" :
42
+ main ()
0 commit comments