Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement DFS (Depth First Search) using sql?

I wonder if the dfs implementation is possible via Sql or some tools based on sql like Informatica, Talend etc. Traversal says for a particular tree

        V1
   V2        V3
V4    V5   V6    V7

       V8

V1 has V2,8,3

V2 has V4,5

V3 has V6,7

V4,5,6,7 has V8 connected

The dfs is V12485673.

       Vertices     NodeRelated
       1                   2
       1                   3
       1                   8
       2                   4
       2                   5
       3                   6
       3                   7
       4                   8
       5                   8
       6                   8
       7                   8
       8                   null

O/p is 12485673

like image 281
Himanshu Avatar asked Jun 09 '26 05:06

Himanshu


1 Answers

Depth first search is exactly the way how connect by traverses hierarchies. So rownum assigned when connect by produces rowsource can be used to define an order.

vertices will appear in result more than once when particular parent has more than one child. noderelated will appear more than once when given node has more than one parent.

In your case both conditions are met thus both vertices/noderelated have "duplicates" but in order to return unique nodes and preserve DFS order you can rely on min(rownum) as shown below.

with t (vertices, noderelated) as
(
select 1, 2 from dual
union all select 1, 3 from dual
union all select 1, 8 from dual
union all select 2, 4 from dual
union all select 2, 5 from dual
union all select 3, 6 from dual
union all select 3, 7 from dual
union all select 4, 8 from dual
union all select 5, 8 from dual
union all select 6, 8 from dual
union all select 7, 8 from dual
union all select 8, null from dual
)
select listagg(vertices, ', ') within group (order by min(rownum)) result
  from t
start with vertices = 1
connect by prior noderelated = vertices
group by vertices;

RESULT
------------------------------
1, 2, 4, 8, 5, 3, 6, 7
like image 109
Dr Y Wit Avatar answered Jun 11 '26 20:06

Dr Y Wit