Skip to main content
6 of 8
edited body
flawr
  • 43.9k
  • 7
  • 104
  • 249

Haskell, 212 bytes

This is probably way too long, but it finally works now. (Thanks to @Lynn for the cartesian product trick!)

import Data.List
b%l=[l++[x|b/=last l,x`notElem`l,1==sum[1|(u,v)<-x`zip`last l,u/=v]]|x<-mapM id[[1>0,1<0]|_<-b]]
b!a|f<-nub.concat.((b%)<$>)=snd$maximum$map(length>>=(,))$filter((==b).last)$until(f>>=(==))f[[a]]

Try it online!

flawr
  • 43.9k
  • 7
  • 104
  • 249