|
楼主 |
发表于 2024-9-24 14:20
|
显示全部楼层
with recursive q as
(select 'hit' beginWord , 'cog' endWord, ['hit','hot','dot','dog','lot','log','cog'] wordList)
,a as(select unnest(wordlist)w,unnest(range(length(wordlist)))n from q where list_has(wordlist,beginWord)
union all
select unnest(wordlist+[beginWord])w,unnest(range(1+length(wordlist)))n from q where not list_has(wordlist,beginWord)
)
,t as (select a.w,b.w w2,a.n,b.n n2 from a,a b where exists(select 1 from range(1,10)t(i) where a.n<>b.n and i<=length(a.w)
and substr(a.w,1,i-1)||substr(a.w,i+1)=substr(b.w,1,i-1)||substr(b.w,i+1)))
,x as (select 1 lv, beginword b,b path,0 m from q
union all
select lv+1, w2 ,path||','||w2, m+(1<< n2) from x,t where x.b=t.w and x.b<> (select endword from q) and m & (1<<n2)=0)
from x where b=(select endword from q) order by lv limit 1;
┌───────┬─────────┬─────────────────────┬───────┐
│ lv │ b │ path │ m │
│ int32 │ varchar │ varchar │ int32 │
├───────┼─────────┼─────────────────────┼───────┤
│ 5 │ cog │ hit,hot,lot,log,cog │ 114 │
└───────┴─────────┴─────────────────────┴───────┘
Run Time (s): real 0.080 user 0.327602 sys 0.031200
|
|